I am trying to run a python script overnight on a Raspberry Pi, starting at 1900 and finishing at 0700, which scans the environment around the machine for MAC addresses of nearby devices for security using a TP Link WIFI dongle. Although scheduling the program is straightforward, I see no way to get it to stop running automatically at 0700 every day. As I understand it cron is only for starting tasks. Is there any other way to do this? Thanks.
As goldilocks points out, the cleanest way to do this would be for the script to stop itself.
Alternatively, you could execute a cron job to kill the process you launched. To do this in a script, you'd need to first find the process IDs to kill using
pgrep -f "full process name"
That should output a list of PIDs which match:
Note that the
-f option searches the full process names, but you can just put in a fragment of the full process name (e.g. just the call to Python and your script name) and it should work. If you can't find the full process name, you can list all processes with
ps aux and look through the output.
We can then pipe it into
xargs to run
kill for each PID:
pgrep -f "full process name" | xargs kill
If you run that command in a cron job set to 07:00, that should kill the process. It would be wise to test it first (e.g. launch a cron job, then kill it 5 minutes later) to test that the setup works correctly, but this should do the trick.