源码如下:(Tornado 4.0.2)
-
class PeriodicCallback(object):
-
"""Schedules the given callback to be called periodically.
-
-
The callback is called every ``callback_time`` milliseconds.
-
-
`start` must be called after the `PeriodicCallback` is created.
-
"""
-
def __init__(self, callback, callback_time, io_loop=None):
-
self.callback = callback
-
if callback_time <= 0:
-
raise ValueError("Periodic callback must have a positive callback_time")
-
self.callback_time = callback_time
-
self.io_loop = io_loop or IOLoop.current()
-
self._running = False
-
self._timeout = None
-
-
def start(self):
-
"""Starts the timer."""
-
self._running = True
-
self._next_timeout = self.io_loop.time()
-
self._schedule_next()
-
-
def stop(self):
-
"""Stops the timer."""
-
self._running = False
-
if self._timeout is not None:
-
self.io_loop.remove_timeout(self._timeout)
-
self._timeout = None
-
-
def _run(self):
-
if not self._running:
-
return
-
try:
-
return self.callback()
-
except Exception:
-
self.io_loop.handle_callback_exception(self.callback)
-
finally:
-
self._schedule_next()
-
-
def _schedule_next(self):
-
if self._running:
-
current_time = self.io_loop.time()
-
while self._next_timeout <= current_time:
-
self._next_timeout += self.callback_time / 1000.0
-
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
PeriodicCallback类用来周期的调用一个callback函数。一般如下方式使用:
-
obj = PeriodicCallback(callback=callback, callback_time=callback_time, io_loop=io_loop)
-
obj.start()
-
......
-
obj.stop()
在__init__()函数中,检验callback_time值的合法性,并将PeriodicCallback实例的状态设置为False,当前的_timeout为None,_timeout用来标识ioloop中的一个定时运行项目,可以向ioloop中添加或从其中移除。调用start()函数时,将实例的状态设置为True,表示这个周期回调的实例正在运行,并且获得ioloop的当前时间,之后每隔一个或多个callback_time时间调用一次callback。在start()函数中调用了_schedule_next()函数,在_schedule_next()函数中,将_run()函数添加到ioloop中,当_run()函数调用时,执行callback回调函数,然后重新调用__schedule_next()函数,直到该实例的stop()函数被调用。在_schedule_next()函数中,获得下一个callback的调用时刻,然后将调用时刻和_run()函数传给ioloop生成一个_timeout用来标识这个周期调用。
阅读(6300) | 评论(0) | 转发(0) |