本文整理汇总了Python中tornado.ioloop.PeriodicCallback.stop方法的典型用法代码示例。如果您正苦于以下问题:Python PeriodicCallback.stop方法的具体用法?Python PeriodicCallback.stop怎么用?Python PeriodicCallback.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.ioloop.PeriodicCallback
的用法示例。
在下文中一共展示了PeriodicCallback.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_game
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
def start_game():
''' Main entry point for the application '''
cache_actions()
sockets = netutil.bind_sockets(8888)
#if process.task_id() == None:
# tornado.process.fork_processes(-1, max_restarts = 10)
server = HTTPServer(application)
server.add_sockets(sockets)
io_loop = IOLoop.instance()
session_manager = SessionManager.Instance()
if process.task_id() == None:
scoring = PeriodicCallback(scoring_round, application.settings['ticks'], io_loop = io_loop)
session_clean_up = PeriodicCallback(session_manager.clean_up, application.settings['clean_up_timeout'], io_loop = io_loop)
scoring.start()
session_clean_up.start()
try:
for count in range(3, 0, -1):
logging.info("The game will begin in ... %d" % (count,))
sleep(1)
logging.info("Good hunting!")
io_loop.start()
except KeyboardInterrupt:
if process.task_id() == 0:
print '\r[!] Shutdown Everything!'
session_clean_up.stop()
io_loop.stop()
示例2: WSHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
with q_live.mutex:
q_live.queue.clear()
self.callback = PeriodicCallback(self.send_werte, 1)
self.callback.start()
print ('Connection open')
def send_werte(self):
if not q_live.empty():
signals, values = q_live.get()
senden = dict(zip(signals,values))
print(senden)
json_send = json.dumps(senden)
self.write_message(json_send)
print(q_live.qsize())
if q_live.qsize() >15:
with q_live.mutex:
q_live.queue.clear()
def on_message(self, empf):
print('Daten recievied: ')
def on_close(self):
print('Connection closed!')
self.callback.stop()
示例3: SendWebSocket
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class SendWebSocket(tornado.websocket.WebSocketHandler):
#on_message -> receive data
#write_message -> send data
def __init__(self, *args, **keys):
self.i = 0
super(SendWebSocket, self).__init__(*args, **keys)
def open(self):
self.callback = PeriodicCallback(self._send_message, 1)
self.callback.start()
print "WebSocket opend"
def on_message(self, message):
print message
def _send_message(self):
self.i += 1
self.write_message(str(self.i))
if self.i % 20 == 0:
self.write_message("\n")
def on_close(self):
self.callback.stop()
print "WebSocket closed"
示例4: SocketHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class SocketHandler(WebSocketHandler):
def check_origin(self, origin):
"""
Overrides the parent method to return True for any request, since we are
working without names
:returns: bool True
"""
return True
def open(self):
logging.info("Connection open from " + self.request.remote_ip)
if not self in statusmonitor_open_sockets:
statusmonitor_open_sockets.append(self) #http://stackoverflow.com/a/19571205
self.callback = PeriodicCallback(self.send_data, 1000)
self.callback.start()
start_callback()
def send_data(self):
self.write_message(data_json)
return
def on_close(self):
self.callback.stop()
if self in statusmonitor_open_sockets:
statusmonitor_open_sockets.remove(self)
stop_callback()
def send_update(self):
pass
示例5: WebSocketconnectionsHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WebSocketconnectionsHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
logger.debug("Creating WebSocket connections handler")
super(WebSocketconnectionsHandler, self).__init__(*args, **kwargs)
# No WebSocket connection yet
self.connected = False
# We have not counted the connections yet
self.connections = 0
# Update the connection count
self.update()
# Setup periodic callback via Tornado
self.periodic_callback = PeriodicCallback(getattr(self, 'update'), 1000)
def get_connections(self):
self.connections = 0
# Get all connections using psutil
conn = psutil.net_connections('inet')
if ws.config.CONFIG['PORT'][0] == 'all':
# If we need the count for all ports we've got it.
for connection in conn:
self.connections += 1
else:
# Isolate date for the requested ports.
for port in ws.config.CONFIG['PORT']:
for connection in conn:
if connection.laddr[1] == int(port):
self.connections += 1
return(self.connections)
def update(self):
# Save the old number of connections
old = self.connections
self.get_connections()
# Check if the number of connections has changed
if old != self.connections:
# Send the new data.
if self.connected:
logger.debug(json.dumps({ "connections": self.get_connections() }))
self.write_message(json.dumps({ "connections": self.get_connections() }))
def open(self):
logger.debug(json.dumps({ "connections": self.get_connections() }))
self.write_message(json.dumps({ "connections": self.get_connections() }))
# We have a WebSocket connection
self.connected = True
self.periodic_callback.start()
def on_message(self, message):
logger.debug(json.dumps({ "connections": self.get_connections() }))
self.write_message(json.dumps({ "connections": self.get_connections() }))
def on_close(self):
logger.debug("Connection closed")
# We no longer have a WebSocket connection.
self.connected = False
self.periodic_callback.stop()
示例6: WebSocketChatHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WebSocketChatHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
self.clients = []
self.callback = PeriodicCallback(self.update_chat, 500)
self.web_gui_user = self.player_manager.get_by_name(self.get_secure_cookie("player"))
def open(self, *args):
self.clients.append(self)
for msg in self.messages_log:
self.write_message(msg)
self.callback.start()
def on_message(self, message):
messagejson = json.loads(message)
self.messages.append(message)
self.messages_log.append(message)
self.factory.broadcast("^yellow;<{d}> <^red;{u}^yellow;> {m}".format(
d=datetime.now().strftime("%H:%M"), u=self.web_gui_user.name, m=messagejson["message"]), 0, "")
def update_chat(self):
if len(self.messages) > 0:
for message in sorted(self.messages):
for client in self.clients:
client.write_message(message)
del self.messages[0:len(self.messages)]
def on_close(self):
self.clients.remove(self)
self.callback.stop()
示例7: WSHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WSHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
self.values = [[], []]
def check_origin(self, origin):
return True
def open(self):
# Send message periodic via socket upon a time interval
self.initialize()
self.callback = PeriodicCallback(self.send_values, timeInterval)
self.callback.start()
def send_values(self):
MAX_POINTS = 30
# Generates random values to send via websocket
for val in self.values:
if len(val) < MAX_POINTS:
val.append(randint(1, 10))
else:
val.pop(0)
val.append(randint(1, 10))
# self.values1 = [randint(1,10) for i in range(100)]
message = {"Channel0": self.values[0], "Channel1": self.values[1]}
# self.write_message(message)
message = {"DataInfo": [{"id": 40, "sname": "SOG"}]}
self.write_message(message)
def on_message(self, message):
pass
def on_close(self):
self.callback.stop()
示例8: SendWebSocketHandler
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class SendWebSocketHandler(tornado.websocket.WebSocketHandler):
# on_message recieve data
# write_message send data
def open(self):
self.callback = PeriodicCallback(self._send_message, 10000)
self.callback.start()
print("[START] WebSocket")
def on_message(self, message):
print("[START] WebSocket on_message")
print(message)
def _send_message(self):
cur = DB.execute("SELECT * FROM lm35dz ORDER BY YMDHHMM DESC")
rec = cur.fetchone()
send_value = ""
if rec == None:
send_value = "Data Nothing"
else:
send_value = "%s %s" % (rec[0], rec[1])
self.write_message(send_value)
def on_close(self):
self.callback.stop()
print("[ENDED] WebSocket")
示例9: LoLAPI
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class LoLAPI(object):
def __init__(self, client):
self.timer = PeriodicCallback(self.status, 1000, IOLoop.instance())
self.client = client
self.timer.start()
def status(self):
self.client.one.update_status(dict(
last_updated = datetime.now().strftime("%H:%M:%S %d-%m-%y"),
game_stats = db.games_data.count(),
players = db.users.count(),
full_games = db.games.count(),
invalid_games = db.invalid_games.count()
))
def set_user(self, name):
self.user = User.by_name(name)
stats = GameStats.find(dict(summoner = self.user.get_dbref()))
games = [Game.find_one(stat['game_id']) for stat in stats]
self.client.one.update_games([1, 2, 3, 4, 5, 6, 7])
# self.client.one.update_games(list(stats))
def detach(self):
self.timer.stop()
示例10: WebSocket
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WebSocket(tornado.websocket.WebSocketHandler):
waiters = set() # multi clients connect OK
wdata = ""
def open(self):
print("open websocket connection")
WebSocket.waiters.add(self) # client add
self.callback = PeriodicCallback(self._send_message, 30000) # time out taisaku
self.callback.start()
def on_close(self):
WebSocket.waiters.remove(self) # client remove
self.callback.stop()
print("close websocket connection")
def on_message(self, message):
WebSocket.wdata = message
WebSocket.send_updates(message)
@classmethod
def send_updates(cls, message): # this method is singleton
print(message + ":connection=" + str(len(cls.waiters)))
for waiter in cls.waiters:
try:
waiter.write_message(message)
except:
print("Error sending message", exc_info=True)
# TIME OUT BOUSHI CALL BACK 30Sec
def _send_message(self):
self.write_message("C:POLLING")
示例11: WebSocketGame
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WebSocketGame(WebSocketHandler):
def open(self):
self.game_data = {}
self.initialize_game()
self.write_message(self.game_data)
def on_message(self, message):
message = json.loads(message)
if message["type"] == "login":
self.game_name = message["name"]
self.game_id = message["game_id"]
self.loop_callback = PeriodicCallback(self.do_loop, 5000)
else:
self.handle_message(message)
def on_close(self):
self.loop_callback.stop()
pass
def update_status(self, status):
if status not in ("S", "I", "U", "F"): # Start, InProgress, Succesful, Fail
return # Let's try not to hit the status API with bad values.
url = "http://localhost:8080/private_api/gametask/{}/{}/{}".format(self.game_name, self.game_id, status)
request = HTTPRequest(url=url)
http = AsyncHTTPClient()
http.fetch(request, self.callback)
def callback(self, response):
# Catch any errors.
print "Callback fired."
print "HTTP Code: {}".format(response.code)
示例12: broadcast_players
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
def broadcast_players(g_id):
global pcb2
global cur_g_id
data_dict = {}
if pcb2 is None:
cur_g_id = g_id
pcb2 = PeriodicCallback(lambda: broadcast_players(g_id), 4000)
pcb2.start()
elif cur_g_id != g_id:
cur_g_id = g_id
pcb2.stop()
pcb2 = PeriodicCallback(lambda: broadcast_players(g_id), 4000)
pcb2.start()
g_list = ww_redis_db.keys(g_id+"*")
for v in g_list:
v = v.decode("utf-8")
if len(g_list) > 0:
# find game with least spaces
for g_key in g_list:
game = ww_redis_db.hgetall(g_key)
game = {k.decode('utf8'): v.decode('utf8') for k, v in game.items()} #convert from byte array to string dict
players = game['players'].split("|") # obtain players in current game in the form of uuid
data_dict[g_key.decode("utf-8")] = str(len(players))
data_dict["channel"] = "player_list"
publish_data("player_list:"+g_id, data_dict)
return data_dict
示例13: cpustatus
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class cpustatus(tornado.websocket.WebSocketHandler):
#on_message -> receive data
#write_message -> send data
#index.html
def open(self):
#self.i = readData()
self.i = 0
self.last = 0
self.cpu = PeriodicCallback(self._send_cpu, 500) #
self.cpu.start()
def on_message(self, message):
global MainMotorMax
self.i = int(message)
MainMotorMax = self.i
print message
def _send_cpu(self):
#self.write_message(str(vmstat()[15]))
#self.write_message(str(time.time()))
#self.i = readData()
if self.i != self.last:
self.write_message(str(self.i))
self.last = self.i
print self.i
#
def on_close(self):
self.cpu.stop()
示例14: WebSocket
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class WebSocket(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
# Start an infinite loop when this is called
if message == "read_camera":
self.camera_loop = PeriodicCallback(self.loop, 10)
self.camera_loop.start()
# Extensibility for other methods
else:
print("Unsupported function: " + message)
def loop(self):
"""Sends camera images in an infinite loop."""
bio = io.BytesIO()
if args.use_usb:
_, frame = camera.read()
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
img.save(bio, "JPEG")
else:
camera.capture(bio, "jpeg", use_video_port=True)
try:
self.write_message(base64.b64encode(bio.getvalue()))
except tornado.websocket.WebSocketClosedError:
self.camera_loop.stop()
示例15: EventedStatsCollector
# 需要导入模块: from tornado.ioloop import PeriodicCallback [as 别名]
# 或者: from tornado.ioloop.PeriodicCallback import stop [as 别名]
class EventedStatsCollector(StatsCollector):
"""
Stats Collector which allows to subscribe to value changes.
Update notifications are throttled: interval between updates is no shorter
than ``accumulate_time``.
It is assumed that stat keys are never deleted.
"""
accumulate_time = 0.1 # value is in seconds
def __init__(self, crawler):
super(EventedStatsCollector, self).__init__(crawler)
self.signals = SignalManager(self)
self._changes = {}
self._task = PeriodicCallback(self.emit_changes, self.accumulate_time*1000)
self._task.start()
# FIXME: this is ugly
self.crawler = crawler # used by ArachnadoCrawlerProcess
def emit_changes(self):
if self._changes:
changes, self._changes = self._changes, {}
self.signals.send_catch_log(stats_changed, changes=changes)
def open_spider(self, spider):
super(EventedStatsCollector, self).open_spider(spider)
self._task.start()
def close_spider(self, spider, reason):
super(EventedStatsCollector, self).close_spider(spider, reason)
self._task.stop()