Ubuntu 16.04 The program running under screen often crashes and I often have to manually reboot. How to set up auto-restart 3 times a day. ( I mean crontab to shut down it and run it again )


2 Answers 2


HostFission's solution is good, but if you don't want to check if the program is running you can also kill it and start it like this:

Create a bash file with any name on it (like: restart.sh) and type this:


/usr/bin/screen -SX NameOfTheScreen quit;

/usr/bin/screen -S NameOfTheScreen /path/to/startscript;

-S sets the session name -X executes something on the session

Be careful not to use -S -X name, as this will name the session -X. Use - SX name instead.

Then you can set-up crontab to execute this file as many times as you want during the day.

crontab -e

* 3,6,9,12,15,18,21,0 * * * /path/to/restart.sh >> /path/to/logfile


You need to store the PID of the running process somewhere when it launches, and then later if it is still running send a SIGTERM to the process and wait for it to terminate. The below script will perform these actions.


if [ -f $PIDFILE ]; then
  PID = $(cat $PIDFILE)
  if [ -d /proc/$PID ] && [ "$(readlink -f /proc/$PID/exe)" == "$PROGRAM" ]; then
    echo -n "Shutting down..."
    kill $PID
    wait $PID
    echo "done."
    echo "PID not found, program already terminated."

echo -n "Starting..."
echo $! > $PIDFILE
echo "done."

Then just schedule this in cron to run every X hours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.