我想用我扭曲的应用程序实现一个类似cron的行为。我想要触发一个周期性的调用(比如说每周),但是只在一个精确的时间运行,而不是在我启动应用程序的时候。
我的用例如下:我的python应用程序在一周中的任何时候启动。我希望通话时间是每周一早上8点但我不想执行活动等待(使用time.sleep()),我希望使用callLater在下周一触发调用,然后从该日期开始循环调用。
有什么想法/建议吗?谢谢,J。
发布于 2013-01-31 18:18:22
如果您非常喜欢cron风格的说明符,那么也可以考虑使用parse-crontab。
那么你的代码看起来基本上是这样的:
from crontab import CronTab
monday_morning = CronTab("0 8 * * 1")
def do_something():
reactor.callLater(monday_morning.next(), do_something)
# do whatever you want!
reactor.callLater(monday_morning.next(), do_something)
reactor.run()
发布于 2013-01-29 10:48:51
如果我正确理解了您的问题,您正在考虑的是计划任务的第一次执行,以及如何提供应用程序的初始启动时间。如果是这种情况,您只需要计算TimeDelta值(单位为秒)就可以传递给callLater。
import datetime
from twisted.internet import reactor
def cron_entry():
full_weekseconds = 7*24*60*60
print "I was called at a specified time, now you can add looping task with a full weekseconds frequency"
def get_seconds_till_next_event(isoweekday,hour,minute,second):
now = datetime.datetime.now()
full_weekseconds = 7*24*60*60
schedule_weekseconds = ((((isoweekday*24)+hour)*60+minute)*60+second)
now_weekseconds=((((now.isoweekday()*24)+now.hour)*60+now.minute)*60+now.second)
if schedule_weekseconds > now_weekseconds:
return schedule_weekseconds - now_weekseconds
else:
return now_weekseconds - schedule_weekseconds + full_weekseconds
initial_execution_timedelta = get_seconds_till_next_event(3,2,25,1)
"""
This gets a delta in seconds between now and next Wednesday -3, 02 hours, 25 minutes and 01 second
"""
reactor.callLater(initial_execution_timedelta,cron_entry)
reactor.run()
https://stackoverflow.com/questions/14580086
复制相似问题