def __init__(self, name, app, client_ttl=300): self.name = name self.app = app self.__session = None self.client_ttl = timedelta(seconds=client_ttl) self.clients = {} self.register_handlers() self._stale_manager = PeriodicTask(self.cull_clients, client_ttl//2).start()
def main(port): db_session.add(database.CupModel()) db_session.commit() greyscale = GreyscaleResource() humidity = HumidityResource() liquid = LiquidResource() temperature = TemperatureResource() PeriodicTask(greyscale.update, 5) PeriodicTask(humidity.update, 5) PeriodicTask(liquid.update, 5) PeriodicTask(temperature.update, 5) root = resource.Site() root.add_resource(('g',), greyscale) root.add_resource(('h',), humidity) root.add_resource(('l',), liquid) root.add_resource(('t',), temperature) asyncio.Task(aiocoap.Context.create_server_context(root, bind=('::', port))) asyncio.get_event_loop().run_forever()
async def register_with_manager(self): url = urljoin(self.manager_url, 'register') data = {'url': self.worker_host, 'port': self.port} print("registering with:", url) async with self._session.get(url, json=data) as resp: response = await resp.json() self.client_id = response['client_id'] self.key = response['key'] print("I am now:", self.client_id) if self._heartbeat_manager is not None: await self._heartbeat_manager.stop() self._heartbeat_manager = PeriodicTask( self.heartbeat, self.heartbeat_time, ).start()
serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app def ws_interval(app=None): ''' Send to all users empty message to avoid nginx timeout ''' for key, game in app['websockets'].items(): for ws in game: ws.send_str( json.dumps({ 'message': 'pong', 'status': STATUS['INFO'] })) if __name__ == '__main__': loop = asyncio.get_event_loop() serv_generator, handler, app = loop.run_until_complete(init(loop)) serv = loop.run_until_complete(serv_generator) # Create periodic task task = PeriodicTask(lambda: ws_interval(app), PONG_WS_INTERVAL) log.debug('start server %s' % str(serv.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: log.debug('Stop server begin') finally: loop.run_until_complete(shutdown(serv, app, handler)) loop.close() log.debug('Stop server end')