0

I was wondering if my crontab jobs were written correctly. I am hoping to run them on a VPS and monitoring them isn't really possible. Without further ado here are my cron jobs:

# cd into directory at 2:57 AM 
57 2 * * 1-5 cd /folder_name

# activate the virtual environment
58 2 * * 1-5 . env/bin/activate

# run the main script
59 2 * * 1-5 python main.py

# at 5pm break the script (worried the most about this part)
0 16 * * 1-5 ^C

Also I changed my system clock to be eastern time, does that mean the cron jobs will run using the eastern time zone?

2 Answers 2

1

No, cron is not a shell. Write a script:

#!/bin/sh
cd /folder_name
. env/bin/activate
exec python main.py

Make it executable, then point a crontab entry to it:

57 2 * * 1-5 /path/to/script

The script should then run every Monday to Friday, at 2:57 in (your machine's idea of) local timezone. If you configured your mail system properly the results (if any) are mailed to you.

2
  • Just curious, but if I added: 0 16 * * 1-5 /usr/bin/sh killall -9 main.py to my crontab would that stop my python script (also do I have to specify where main.py is, like /folder_name/main.py)
    – ng150716
    Commented Oct 28, 2016 at 21:50
  • @ng150716 Does that command work if you run it from a terminal? If it doesn't, why not? (Rhetorical questions, you don't need to post the answers). Commented Oct 29, 2016 at 7:00
0

Your cron jobs are not written correctly. Every cron job gets its own environment, which means the cd command has no bearing on the following cronjobs.

As far as virtual environments, I suggest you manually activate the virtual environment, and then run which python yourself. That will give you a full path to a python that will always run in that virtual environment. You should use this python path in your cron.

Final crontab should look something like this:

0 3 * * 1-5 /full/path/to/virtualenv/python /full/path/to/main.py

As far as killing the process later, the most common solution to this problem is by using a pidfile. There are python libraries to help you do this. This Answer is fairly thorough on that subject, but is not really related to the crontab question.

2
  • How about: 0 16 * * 1-5 /usr/bin/sh killall -9 main.py? Would that stop my python script (also do I have to specify where main.py is, like /folder_name/main.py)
    – ng150716
    Commented Oct 28, 2016 at 21:51
  • I am not sure, but I don't think so. I am fairly sure the process will be python. You also run the risk of killing other tasks run by python (or called main.py if your way happens to work).
    – ckeeney
    Commented Nov 1, 2016 at 3:47

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.