def start(io_loop=None, check_time=500):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
"""
io_loop = io_loop or ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
gen_log.warning("tornado.autoreload started more than once in the same process")
if _has_execv:
add_reload_hook(functools.partial(io_loop.close, all_fds=True))
modify_times = {}
callback = functools.partial(_reload_on_update, modify_times)
scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
scheduler.start()
python类PeriodicCallback()的实例源码
def test_overrun(self):
sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]
expected = [
1010, 1020, 1030, # first 3 calls on schedule
1050, 1070, # next 2 delayed one cycle
1100, 1130, # next 2 delayed 2 cycles
1170, 1210, # next 2 delayed 3 cycles
1220, 1230, # then back on schedule.
]
calls = []
def cb():
calls.append(self.io_loop.time())
if not sleep_durations:
self.io_loop.stop()
return
self.io_loop.sleep(sleep_durations.pop(0))
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.start()
self.assertEqual(calls, expected)
def start(io_loop=None, check_time=500):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
"""
io_loop = io_loop or ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
gen_log.warning("tornado.autoreload started more than once in the same process")
if _has_execv:
add_reload_hook(functools.partial(io_loop.close, all_fds=True))
modify_times = {}
callback = functools.partial(_reload_on_update, modify_times)
scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
scheduler.start()
def test_overrun(self):
sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]
expected = [
1010, 1020, 1030, # first 3 calls on schedule
1050, 1070, # next 2 delayed one cycle
1100, 1130, # next 2 delayed 2 cycles
1170, 1210, # next 2 delayed 3 cycles
1220, 1230, # then back on schedule.
]
calls = []
def cb():
calls.append(self.io_loop.time())
if not sleep_durations:
self.io_loop.stop()
return
self.io_loop.sleep(sleep_durations.pop(0))
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.start()
self.assertEqual(calls, expected)
def start(io_loop=None, check_time=500):
"""Begins watching source files for changes.
.. versionchanged:: 4.1
The ``io_loop`` argument is deprecated.
"""
io_loop = io_loop or ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
gen_log.warning("tornado.autoreload started more than once in the same process")
if _has_execv:
add_reload_hook(functools.partial(io_loop.close, all_fds=True))
modify_times = {}
callback = functools.partial(_reload_on_update, modify_times)
scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
scheduler.start()
def test_overrun(self):
sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]
expected = [
1010, 1020, 1030, # first 3 calls on schedule
1050, 1070, # next 2 delayed one cycle
1100, 1130, # next 2 delayed 2 cycles
1170, 1210, # next 2 delayed 3 cycles
1220, 1230, # then back on schedule.
]
calls = []
def cb():
calls.append(self.io_loop.time())
if not sleep_durations:
self.io_loop.stop()
return
self.io_loop.sleep(sleep_durations.pop(0))
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.start()
self.assertEqual(calls, expected)
def __init__(self, *args, **kwargs):
self.io_loop = IOLoop.current()
self.creation_times = {}
if 'timeout' in kwargs:
self.timeout = kwargs.pop('timeout')
if 'interval' in kwargs:
self.interval = kwargs.pop('interval')
super(AutoExpireDict, self).__init__(*args, **kwargs)
# Set the start time on every key
for k in self.keys():
self.creation_times[k] = datetime.now()
self._key_watcher = PeriodicCallback(
self._timeout_checker, self.interval, io_loop=self.io_loop)
self._key_watcher.start() # Will shut down at the next interval if empty
def interval(self, value):
if isinstance(value, basestring):
value = convert_to_timedelta(value)
if isinstance(value, timedelta):
value = total_seconds(value) * 1000 # PeriodicCallback uses ms
self._interval = value
# Restart the PeriodicCallback
if hasattr(self, '_key_watcher'):
self._key_watcher.stop()
self._key_watcher = PeriodicCallback(
self._timeout_checker, value, io_loop=self.io_loop)
def __del__(self):
"""
Ensures that our `tornado.ioloop.PeriodicCallback`
(``self._key_watcher``) gets stopped.
"""
self._key_watcher.stop()
def initialize(self, io_loop, max_clients=10, defaults=None):
super(CurlAsyncHTTPClient, self).initialize(io_loop, defaults=defaults)
self._multi = pycurl.CurlMulti()
self._multi.setopt(pycurl.M_TIMERFUNCTION, self._set_timeout)
self._multi.setopt(pycurl.M_SOCKETFUNCTION, self._handle_socket)
self._curls = [self._curl_create() for i in range(max_clients)]
self._free_list = self._curls[:]
self._requests = collections.deque()
self._fds = {}
self._timeout = None
# libcurl has bugs that sometimes cause it to not report all
# relevant file descriptors and timeouts to TIMERFUNCTION/
# SOCKETFUNCTION. Mitigate the effects of such bugs by
# forcing a periodic scan of all active requests.
self._force_timeout_callback = ioloop.PeriodicCallback(
self._handle_force_timeout, 1000, io_loop=io_loop)
self._force_timeout_callback.start()
# Work around a bug in libcurl 7.29.0: Some fields in the curl
# multi object are initialized lazily, and its destructor will
# segfault if it is destroyed without having been used. Add
# and remove a dummy handle to make sure everything is
# initialized.
dummy_curl_handle = pycurl.Curl()
self._multi.add_handle(dummy_curl_handle)
self._multi.remove_handle(dummy_curl_handle)
def test_basic(self):
calls = []
def cb():
calls.append(self.io_loop.time())
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.call_later(50, self.io_loop.stop)
self.io_loop.start()
self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])
def test_basic(self):
calls = []
def cb():
calls.append(self.io_loop.time())
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.call_later(50, self.io_loop.stop)
self.io_loop.start()
self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])
def initialize(self, io_loop, max_clients=10, defaults=None):
super(CurlAsyncHTTPClient, self).initialize(io_loop, defaults=defaults)
self._multi = pycurl.CurlMulti()
self._multi.setopt(pycurl.M_TIMERFUNCTION, self._set_timeout)
self._multi.setopt(pycurl.M_SOCKETFUNCTION, self._handle_socket)
self._curls = [self._curl_create() for i in range(max_clients)]
self._free_list = self._curls[:]
self._requests = collections.deque()
self._fds = {}
self._timeout = None
# libcurl has bugs that sometimes cause it to not report all
# relevant file descriptors and timeouts to TIMERFUNCTION/
# SOCKETFUNCTION. Mitigate the effects of such bugs by
# forcing a periodic scan of all active requests.
self._force_timeout_callback = ioloop.PeriodicCallback(
self._handle_force_timeout, 1000, io_loop=io_loop)
self._force_timeout_callback.start()
# Work around a bug in libcurl 7.29.0: Some fields in the curl
# multi object are initialized lazily, and its destructor will
# segfault if it is destroyed without having been used. Add
# and remove a dummy handle to make sure everything is
# initialized.
dummy_curl_handle = pycurl.Curl()
self._multi.add_handle(dummy_curl_handle)
self._multi.remove_handle(dummy_curl_handle)
def test_basic(self):
calls = []
def cb():
calls.append(self.io_loop.time())
pc = PeriodicCallback(cb, 10000)
pc.start()
self.io_loop.call_later(50, self.io_loop.stop)
self.io_loop.start()
self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])
def main():
if not len(sys.argv) > 1:
print "config file not set"
print "usage: \nrolld config.yml\n"
return
global processes, ioloop
ioloop = IOLoop.instance()
ioloop.add_callback(restart_all)
# pc = PeriodicCallback(periodic_callback, 1000)
# pc.start()
ioloop.start()
def main():
global rolld_proc, nginx_proc
# start rolld
rolld_proc = Subprocess(
shlex.split("rolld example/rolld.yaml"),
stdout=Subprocess.STREAM,
stderr=Subprocess.STREAM,
)
out = partial(out_fn, name='rolld')
rolld_proc.stdout.read_until_close(exit_callback, streaming_callback=out)
rolld_proc.stderr.read_until_close(exit_callback, streaming_callback=out)
# start nginx on port 9091
nginx_proc = Subprocess(
shlex.split("""nginx -p "%s" -c example/nginx.conf""" % os.path.curdir),
stdout=Subprocess.STREAM,
stderr=Subprocess.STREAM,
)
out = partial(out_fn, name='rolld')
nginx_proc.stdout.read_until_close(exit_callback, streaming_callback=out)
nginx_proc.stderr.read_until_close(exit_callback, streaming_callback=out)
# now we restart everything
def send_hub_to_rolld():
print "sending SIGHUP to rolld"
os.kill(rolld_proc.pid, signal.SIGHUP)
def start_ping():
global periodic_checker
periodic_checker = PeriodicCallback(partial(periodic_callback, proc_pid=rolld_proc.pid), 1000)
periodic_checker.start()
IOLoop.instance().add_timeout(time.time() + 5, start_ping)
IOLoop.instance().add_timeout(time.time() + 15, send_hub_to_rolld)
IOLoop.instance().add_timeout(time.time() + 55, exit_test)
def __init__(self, callback, callback_time, io_loop=None):
# PeriodicCallback require callback_time to be positive
warnings.warn("""DelayedCallback is deprecated.
Use loop.add_timeout instead.""", DeprecationWarning)
callback_time = max(callback_time, 1e-3)
super(DelayedCallback, self).__init__(callback, callback_time, io_loop)
def start(self):
pc = PeriodicCallback(lambda: None, 1000, io_loop=self.loop)
self.loop.add_callback(pc.start)
self.loop.add_callback(self.subscription_loop)
yield self.ensure_safe()
def __init__(self):
check_instances = PeriodicCallback(self.check_instances,
ALERT_CHECK_CYCLE * 1000)
check_instances.start()
def open(self, path=''):
self.clientVersion = self.get_argument('version','')
self.msgTime = time.time()
self.locked = ''
self.timeout = None
self.userId = self.get_id_from_cookie()
self.pathUser = (path, self.userId)
self.sessionVersion = self.getSessionVersion(self.get_path_base(path))
self.userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
connectionList = self._connections[self.pathUser[0]][self.pathUser[1]]
if not connectionList:
connectionList.sd_role = self.userRole
connectionList.append(self)
self.pluginInstances = {}
self.awaitBinary = None
if Options['debug']:
print >> sys.stderr, "DEBUG: WSopen", sliauth.iso_date(nosubsec=True), self.pathUser, self.clientVersion
if not self.userId:
self.close()
self.eventBuffer = []
self.eventFlusher = PeriodicCallback(self.flushEventBuffer, EVENT_BUFFER_SEC*1000)
self.eventFlusher.start()
self.write_message_safe(json.dumps([0, 'session_setup', [self.sessionVersion] ]))