1

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.

1
  • 2
    If this is your script, the most straightforward way would be for it to stop itself... – goldilocks Jan 19 '18 at 19:35
1

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:

pgrep -f "full process name"

That should output a list of PIDs which match:

12453
12454

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 kill, using 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.

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.