Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - 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?

like image 633
microo8 Avatar asked Jul 17 '12 13:07

microo8


People also ask

How do I run a function at a specific time in Python?

Schedule lets you run Python functions (or any other callable) periodically at pre-determined intervals using a simple, human-friendly syntax. Schedule Library is used to schedule a task at a particular time every day or a particular day of a week. We can also set time in 24 hours format that when a task should run.

How do I run a Python function every 5 minutes?

With the help of the Schedule module, we can make a python script that will be executed in every given particular time interval. with this function schedule. every(5). minutes.do(func) function will call every 5 minutes.


1 Answers

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() 
like image 146
Jon Clements Avatar answered Sep 23 '22 00:09

Jon Clements