Created
January 25, 2012 08:54
-
-
Save yyuu/1675502 to your computer and use it in GitHub Desktop.
handle periodic jobs on tornado's ioloop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import os | |
| import sys | |
| import time | |
| import tornado.ioloop | |
| class PeriodicServer(object): | |
| def __init__(self, request_callback, io_loop=None, period=1): | |
| self.request_callback = request_callback | |
| self.io_loop = tornado.ioloop.IOLoop.instance() if io_loop is None else io_loop | |
| self.timeouts = [] | |
| self.period = period | |
| def _tick(self): | |
| try: | |
| self.request_callback() | |
| finally: | |
| self.io_loop.add_timeout(time.time() + self.period, self._tick) | |
| def start(self): | |
| timeouts = self.timeouts | |
| self.timeouts = [] | |
| for timeout in timeouts: | |
| self.io_loop.remove_timeout(timeout) | |
| self.timeouts.append(self.io_loop.add_timeout(time.time(), self._tick)) | |
| def stop(self): | |
| for timeout in self.timeouts: | |
| self.io_loop.remove_timeout(timeout) | |
| def run(): | |
| print "hello" | |
| server = PeriodicServer(run) | |
| server.start() | |
| tornado.ioloop.IOLoop.instance().start() | |
| # vim:set ft=python : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment