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?

  • 1
  • 2
    What does your script do? It may be advantageous to have it sleep until the top of the hour and wake up, do it's few minutes of stuff then go back to sleep. Besides killing a job if it's in the middle of updating files can be risky. – WinEunuuchs2Unix Jun 6 '18 at 0:39

It sounds like you want to daemonize, or create a service for, your Python script. This is how other applications start up, and in the right order or at the right times.

You'll want to create a systemd service for your Python script, and then interface with it via systemctl.

systemctl restart mypython
systemctl enable mypython

Once you have your script working this way, you can set up cron to do whatever it is you need, which will probably be to restart the service.

Depending on the goal of your script, and your ability to determine if it is running properly, you could enhance your service to report if it stops running, or even look into solutions such as monit.

As pointed out, this answer provides useful information, but contains out-of-date tools, such as rc.local. Instead of using systemd, you can track the PID of the process, and then kill that process and re-run your script every hour.


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

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

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.