Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to automate script to run every day at specific time?

Currently, I have a python script that only starts once it hits the specified date/time, and never runs again unless I re-specify the date/time:

import datetime, time

start_time = datetime.datetime(2017, 4, 27, 19, 0, 0)

while(True):
    dtn = datetime.datetime.now()

    if dtn >= start_time:
       # Runs the main code once it hits the start_time

But how can I go about making it so that it only runs the code at a specified time, everyday?

Thank you in advance and will be sure to upvote/accept answer

like image 430
Jo Ko Avatar asked Apr 27 '17 22:04

Jo Ko


1 Answers

cronjob is the correct tool for this job.
To create a job on a mac that executes every day at 12:00, open the terminal and type:

env EDITOR=nano crontab -e
0 12 * * *  /full/path/to/python /full/path/to/script.py

CTRL+O and CTRL+X to save and exit.


Notes:

1 - A job is specified in the following format:

enter image description here

2 - To see a list of your active crontab jobs, use the following command:

crontab -l

Tips:

Execute on workdays 1AM:

0 1 * * 1-5 /full/path/to/python /full/path/to/script.py

Execute every 10 minutes:

*/10 * * * * /full/path/to/python /full/path/to/script.py

Log output to file:

*/10 * * * * /full/path/to/python /full/path/to/script.py >> /var/log/script_output.log 2>&1

Note:

  • crontab.guru is a nice website to understand cronjobs
like image 194
Pedro Lobito Avatar answered Oct 25 '22 23:10

Pedro Lobito