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

18,132

Solution 1

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:

Solution 2

Once you determine that the current time has exceeded the start time, increment the start time by the desired interval using a datetime.timedelta object.

import datetime
import time

next_start = datetime.datetime(2017, 4, 27, 19, 0, 0)
while True:
    dtn = datetime.datetime.now()

    if dtn >= next_start:
        next_start += datetime.timedelta(1)  # 1 day
        # do what needs to be done

    time.sleep(AN_APPROPRIATE_TIME)
Share:
18,132
Jo Ko
Author by

Jo Ko

Updated on June 09, 2022

Comments

  • Jo Ko
    Jo Ko almost 2 years

    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