Iniciar una función en un momento dado

Resuelto microo8 asked hace 11 años • 9 respuestas

¿Cómo puedo ejecutar una función en Python , en un momento dado?

Por ejemplo:

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

y ejecutará la función funcel 17/07/2012 a las 15:50:00.

Probé sched.scheduler , pero no inició mi función.

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

¿Qué puedo hacer?

microo8 avatar Jul 17 '12 20:07 microo8
Aceptado

Leyendo los documentos de http://docs.python.org/py3k/library/sched.html :

A partir de eso, necesitamos calcular un retraso (en segundos)...

from datetime import datetime
now = datetime.now()

Luego utilícelo datetime.strptimepara analizar '2012-07-17 15:50:00' (le dejaré la cadena de formato)

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

Luego puedes usar delaypara pasar a una threading.Timerinstancia, por ejemplo:

threading.Timer(delay, self.update).start()
Jon Clements avatar Jul 17 '2012 14:07 Jon Clements

Eche un vistazo al Programador avanzado de Python, APScheduler: http://packages.python.org/APScheduler/index.html

Tienen un ejemplo solo para este caso de uso: 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'])
stephenbez avatar Jan 27 '2014 21:01 stephenbez