Python - Start a Function at Given Time

microo8 picture microo8 · Jul 17, 2012 · Viewed 79.3k times · Source

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?

Answer

Jon Clements picture Jon Clements · Jul 17, 2012

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