You can use monit
as a utility for managing and monitoring bots so you don't have to keep your shell session open.
I have gone over this before with steemd
, so if you want some more context, check out: Using monit to manage steemd
These steps assume you're using ruby
scripts, but it should be possible to use other programming languages. These steps also assume you're using rvm to manage ruby.
Install Monit
$ sudo apt-get install monit
Create file /home/gilligan/mybot/start_mybot.sh
#!/bin/bash
cd $HOME/mybot
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
$HOME/.rvm/scripts/rvm use ruby-2.4.2
nohup $HOME/.rvm/rubies/ruby-2.4.2/bin/ruby mybot.rb > mybot.log 2>&1 & echo $! > $HOME/mybot/nohup_mybot.pid
Note, we're using nohup
to get the pid
. But you can also configure monit
to work without it by looking for your bot using a matching pattern.
Create file /home/gilligan/mybot/stop_mybot.sh
#!/bin/bash
cd $HOME/mybot
/bin/kill `/bin/cat $HOME/mybot/nohup_mybot.pid`
Make them executable
$ chmod +x /home/gilligan/mybot/start_mybot.sh
$ chmod +x /home/gilligan/mybot/stop_mybot.sh
Edit the file /etc/monit/monitrc
$ sudo nano /etc/monit/monitrc
Edit the file as follows:
# uncomment these lines
set httpd port 2812 and
use address localhost # only accept connection from localhost
allow localhost # allow localhost to connect to the server and
# add this to bottom - change gilligan to your username
check process mybot with pidfile /home/gilligan/mybot/nohup_mybot.pid
start program = "/bin/su - gilligan -c /home/gilligan/mybot/start_mybot.sh"
with timeout 60 seconds
stop program = "/bin/su - gilligan -c /home/gilligan/mybot/stop_mybot.sh"
with timeout 60 seconds
Test the new configuration
$ sudo monit -t
If it looks ok, then proceed to ...
Load the new configuration
$ sudo monit reload
Enable the watchdog
$ sudo monit start mybot
That's it. You only have to do the above command once.
You can check monit's status by typing below:
$ sudo monit status
You can also check status from the web console from addresses you authorize.
This will keep your bot running for you (across restarts, even, no need for any cronjobs or multiplexors) and keep you from fighting with your chosen OS. Keep in mind, the default is for monit
to only once a minute, so be patient if you're waiting for it to do something.