Ubuntu – Restart a python script every hour or so

cronpython

So I have a python script that I launch in the terminal by just typing the script name (python SCRIPTNAME.py)

I'm just wondering is it possible to make a script or cron job that simply just stops then starts that python script every hour?

Best Answer

Best approach would be via GNU timeout as in

timeout -k 3600 python3 /path/to/script.py

where -k stands for "kill after" and time in seconds.

So to have the script run, terminate and restart every hour, you could do

while timeout -k 3600 python3 /path/to/script; do
   sleep 2
done

where sleep 2 is merely to add small delay before restarting


Alternatively consider using Threading module in Python to schedule the relevant parts of the script instead. See https://stackoverflow.com/a/50537798/3701431

Related Question