How can I run a command periodically and indefinitely till it’s turned off? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I run a command periodically and indefinitely till it’s turned off? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to run a command every several minutes until I turn it off.

After some searching, I found lots of ways of doing the first half (running a command periodically and indefinitely), what about I want to turn it off?

By “turn it off” probably I mean “turn it off using another shell command”.

Just to clarify want I really want to do, actually I want to run a Python program P periodically until I give some command to stop it.
And just in case that P happens to be running while I’m giving out the stop command, I want it to finish the current run first, and then not to run ever since.


You have two options: Modify the Python script, or write a shell script wrapper.

To modify the Python script:

  1. You should loop around what it is you want to be doing.

  2. Install a signal handler to catch the INT signal (sent by CtrlC) and TERM signal (sent by plain kill). When the signal is caught, set a variable telling the Python script that it should no longer loop. I’m not familiar enough with with Python to be able to tell you how to do this.

Alternative solution: Shell script wrapper, which does the same as the above, but outside the Python script:



trap 'loop_again=0;wait' INT TERM

while (( loop_again )); do
    echo "Kill me with 'kill -9 $$'"
    ./python_script &
    echo "Kill the Python script with 'kill $!'"

This wrapper script starts your Python script in the background, and then waits for it to finish. It then restarts it, indefinitely. It also tells you how to terminate it and the Python script in each iteration.

If you kill the script (using plain kill, not kill -9), or press CtrlC, the loop_again variable is set to zero (which will cause the loop to terminate at the end of the current iteration), and then it waits for the currently running background process to finish before exiting.

If you kill the wrapper script with kill -9 (which is the same as kill -s KILL, sending a KILL signal that can’t be ignored or caught by a signal handler), it will exit, leaving your Python script running in the background until it finishes by itself.

We are here to answer your question about How can I run a command periodically and indefinitely till it’s turned off? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji