我有一个应用程序需要 3 次定期回调 (其中只有一个真正与 ioloop 交互,因为它通过 websocket 将数据推送到)
def make_app():
return tornado.web.Application([
(r"/websocket", WebsocketHandler),
(r"/getData", DataRequestHandler),
])
if __name__ == '__main__':
tornado.ioloop.PeriodicCallback(callback=calculator1, callback_time=500).start()
tornado.ioloop.PeriodicCallback(callback=calculator2, callback_time=1000).start()
tornado.ioloop.PeriodicCallback(callback=push, callback_time=1000).start()
tornado.ioloop.IOLoop.current().start()
我发现这一切都是在主线程中运行的 问题是,因为
calculator2
可能需要超过 500 毫秒才能运行,所以它会阻塞线程,并且 calculator1
可能不会在接下来的 500 毫秒内运行,因为线程被阻塞了
如何在主线程以外的不同线程中正确调度
calculator1
和 calculator2
周期函数?
我不确定如何使函数在 ioloop 线程以外的不同线程中运行
run_in_executor()
方法在单独的线程中运行阻塞任务。
您需要创建另一个函数来定期运行,它将在另一个线程中执行实际的
calculator1
函数。
# create a thread pool
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=8)
def calculator1_runner():
"""This function is for calling the calculator1 function"""
IOLoop.current().run_in_executor(executor, calculator1)
# Register the runner function for periodic execution
tornado.ioloop.PeriodicCallback(
callback=calculator1_runner,
callback_time=500
).start()