0

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)

1
  • Why are you passing killall as an argument to MotionDetector.py ? Commented Jul 21, 2018 at 21:39

1 Answer 1

2

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'

Sign up to request clarification or add additional context in comments.

1 Comment

Why use -f here? Wouldn't you risk killing for example vim MotionDetector.py?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.