Json
Json

Reputation: 670

Stop / Kill a Python script using cron

My goal is to run my python script each day (besides Friday and Saturday) at 10:00 and terminate it by 18:00.

I added the following to the crontab but the second command isn't working.

0 10 * * 0,1,2,3,4 /home/pi/MotionDetector.py
0 18 * * 0,1,2,3,4 /home/pi/MotionDetector.py killall -9 MotionDetector.py 

Using Linux 2.7.9

I tried this solution that worked Via the terminal but not in cron (when I typed the command in the terminal it closed the script right away but when I put it on the crontab it didn't do anything)

Upvotes: 0

Views: 3075

Answers (1)

Shiva
Shiva

Reputation: 2838

For killing the job:

0 18 * * 0,1,2,3,4 /usr/bin/pkill -f MotionDetector.py

pkill kills a process by name. While the default search criteria is to find the process by its full name, -f argument allows you to search by any of the parts in the process name.


Updated solution to account for the scenario raised by @håken-lid:

When the script is executed by cron or by the user, the process name would be in the format:
cron: /home/pi/venv/bin/python /home/pi/MotionDetector.py
user: python MotionDetectory.py

Using simple regex patterns we can kill the process started by,

  • cron or user:

    0 18 * * 0,1,2,3,4 /usr/bin/pkill -f 'python.*MotionDetector.py'

  • only cron

    0 18 * * 0,1,2,3,4 /usr/bin/pkill -f ^'/home/pi/venv/bin/python /home/pi/MotionDetector.py'

Upvotes: 2

Related Questions