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:
You should loop around what it is you want to be doing.
Install a signal handler to catch the
INTsignal (sent by Ctrl–C) and
TERMsignal (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:
#!/bin/sh loop_again=1 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 $!'" wait done
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.
kill the script (using plain
kill -9), or press Ctrl–C, 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.