6

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

Jo Ko
  • 7,225
  • 15
  • 62
  • 120

4 Answers4

14

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:

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
4

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Do you mind explaining the reason for `time.sleep()`? Thank you for the response by the way! – Jo Ko Apr 27 '17 at 22:49
  • It's just a delay before you call `now()` again. In general, if `dtn >= next_start` is false, then it's going to still be false a millisecond later. A good value for `AN_APPROPRIATE_TIME` is `(next_start - datetime.datetime.now()).seconds`, that is, sleep for however many seconds it is until `next_time`. – chepner Apr 27 '17 at 23:01
1

Using Python module apscheduler could be an option.

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()
0

Using a python you could try

in both cases python interpreter must run and may possibly do other stuff while waiting for the right time.

Or as suggested in the comment, you could use other service running on your os for scheduling your python script execution.

Why not a cronjob (linux) or Task Scheduler ( windows)? – Pedro Lobito

Community
  • 1
  • 1
matusko
  • 3,487
  • 3
  • 20
  • 31