Start a Function at Given Time

How can I run a function in Python, at a given time?

For example:

run_it_at(func, '2012-07-17 15:50:00')

and it will run the function func at 2012-07-17 15:50:00.

I tried the sched.scheduler, but it didn't start my function.

import time as time_module
scheduler = sched.scheduler(time_module.time, time_module.sleep)
t = time_module.strptime('2012-07-17 15:50:00', '%Y-%m-%d %H:%M:%S')
t = time_module.mktime(t)
scheduler_e = scheduler.enterabs(t, 1, self.update, ())

What can I do?


Solution 1:

Reading the docs from http://docs.python.org/py3k/library/sched.html:

Going from that we need to work out a delay (in seconds)...

from datetime import datetime
now = datetime.now()

Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)

# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()

You can then use delay to pass into a threading.Timer instance, eg:

threading.Timer(delay, self.update).start()

Solution 2:

Take a look at the Advanced Python Scheduler, APScheduler: http://packages.python.org/APScheduler/index.html

They have an example for just this usecase: http://packages.python.org/APScheduler/dateschedule.html

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

Solution 3:

Might be worth installing this library: https://pypi.python.org/pypi/schedule, basically helps do everything you just described. Here's an example:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

Solution 4:

Here's an update to stephenbez' answer for version 3.5 of APScheduler using Python 2.7:

import os, time
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta


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


scheduler = BackgroundScheduler()
dd = datetime.now() + timedelta(seconds=3)
scheduler.add_job(tick, 'date',run_date=dd, args=['TICK'])

dd = datetime.now() + timedelta(seconds=6)
scheduler.add_job(tick, 'date',run_date=dd, kwargs={'text':'TOCK'})

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()

Solution 5:

I ran into the same issue: I could not get absolute time events registered with sched.enterabs to be recognized by sched.run. sched.enter worked for me if I calculated a delay, but is awkward to use since I want jobs to run at specific times of day in particular time zones.

In my case, I found that the issue was that the default timefunc in the sched.scheduler initializer is not time.time (as in the example), but rather is time.monotonic. time.monotonic does not make any sense for "absolute" time schedules as, from the docs, "The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid."

The solution for me was to initialize the scheduler as

scheduler = sched.scheduler(time.time, time.sleep)

It is unclear whether your time_module.time is actually time.time or time.monotonic, but it works fine when I initialize it properly.