Python: How to automate script to run every day at specific time?
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:
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
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)
Jo Ko
Updated on June 09, 2022Comments
-
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