From 2f186aa728a1cd5f714d041bbcbf556583fbd065 Mon Sep 17 00:00:00 2001 From: Tom Kwong Date: Thu, 15 Apr 2021 00:08:34 -0700 Subject: [PATCH] Auto shutdown and restart bot periodically --- script/run.sh | 15 ++++++++++++++- src/main.jl | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/script/run.sh b/script/run.sh index a1a2230..61d0b05 100755 --- a/script/run.sh +++ b/script/run.sh @@ -1,8 +1,21 @@ #!/bin/bash +# Start the HoJBot program if [[ -z "$HOJBOT_DISCORD_TOKEN" ]]; then echo "Error: please set up HOJBOT_DISCORD_TOKEN environment variable" exit 1 fi -julia --project=. -e 'using HoJBot; start_bot();' +# Default environment settings +: ${RUN_ONCE=no} +: ${RUN_DURATION_MINUTES=360} + +while true; do + echo "`date`: Starting HoJBot..." + julia --project=. -e "using HoJBot, Dates; start_bot(; run_duration = Minute(${RUN_DURATION_MINUTES}));" + if [[ "$RUN_ONCE" == "yes" ]]; then + break + fi + sleep 1 # throttle to avoid a hot loop when the process keep crashing +done +echo "`date`: Program exited normally" diff --git a/src/main.jl b/src/main.jl index f3f8d23..61309ff 100644 --- a/src/main.jl +++ b/src/main.jl @@ -47,6 +47,7 @@ end function start_bot(; commands = active_commands, handlers = handlers_list, + run_duration = Days(365), # run for a very long time by default ) @info "Starting bot... command prefix = $COMMAND_PREFIX" global client = Client(ENV["HOJBOT_DISCORD_TOKEN"]; @@ -56,6 +57,7 @@ function start_bot(; init_commands!(client, commands) # add_help!(client; help = help_message()) open(client) + auto_shutdown(run_duration) wait(client) end @@ -71,6 +73,23 @@ function init_commands!(client::Client, commands) end end +""" + auto_shutdown(run_duration::TimePeriod) + +Run a background process to track the program's run time and exit +the program when it has exceeded the specified `run_duration`. +""" +function auto_shutdown(run_duration::TimePeriod) + start_time = now() + @async while true + if now() > start_time + run_duration + @info "Times up! The bot is shutting down automatically." + exit(0) + end + sleep(5) + end +end + commander(c::Client, m::Message, service) = begin @info "commander" c m service