我的目标很简单:在特定时间启动periodicCallback。我试着到处寻找,但所有读取的例子都与当前时间的时间值有关,而与定义的时间无关。
我写了一个简单的例子。
import tornado.ioloop
import datetime
from datetime import date, time
from tornado.ioloop import IOLoop, PeriodicCallback
def startService():
print("periodic thing")
def periodicCallback():
periodic = PeriodicCallback(callback=startService,callback_time=5000)
periodic.start()
if __name__ == "__main__":
main_loop = IOLoop.instance()
# I want to set a specific time
starting_time = time(14, 30, 00)
# After this time i would want to have the message "periodic thing" every callback_time
(...)
#my first test but i have error about deadline unsupported:
IOLoop.current().add_timeout(starting_time, periodicCallback)
main_loop.start()
感谢您的帮助
答案 0 :(得分:0)
错误 - Unsupported deadline
- 您之后看到的是因为add_timeout
获取了datetime.timedelta
个对象,而您提供了datetime.time
个对象。
由于您希望在特定时间运行回调,因此可以计算到该时间的时间值。
import datetime
# see the current time
now = datetime.datetime.now()
# create a datetime object for your desired time
starting_time = datetime.datetime(year=2018, month=3, day=13,
hour=14, minute=30)
# subtract `now` from `starting_time`
# to calculate timedelta
td = starting_time - now
main_loop.add_timeout(td, periodicCallback)
如果year
或month
或day
与now
时间相同,您也可以这样做:
starting_time = datetime.datetime(year=now.year, month=now.month, day=now.day,
hour=14, minute=30)