Reputation: 125
I'm using autobahn with asyncio and I'm trying to make a method inside a class that extends WebSocketServerFactory run every x seconds.
This is how the documentation on the autobahn website does it:
from autobahn.asyncio.websocket import WebSocketServerFactory
factory = WebSocketServerFactory()
factory.protocol = MyServerProtocol
loop = asyncio.get_event_loop()
coro = loop.create_server(factory, '127.0.0.1', 9000)
server = loop.run_until_complete(coro)
I have simply replaced the WebSocketServerFactory class with a class that extends it, and I want to run a method inside it every x seconds.
I found an example of this on the autobahn website, but it uses twisted and not asyncio.
Here is an short example(original and full version) of what I want, but the example uses twisted:
class CustomServerFactory(WebSocketServerFactory):
def __init__(self, url):
WebSocketServerFactory.__init__(self, url)
self.tick()
def tick(self):
print("tick!")
self.do_something()
reactor.callLater(1, self.tick)
How can I achive the same thing using asyncio?
Upvotes: 0
Views: 707
Reputation: 3265
Based on your example, the same functionality with asyncio can be done using the asyncio event loop: Asyncio delayed calls.
So in your example that would mean something like this:
def tick(self):
print("tick!")
self.do_something()
loop.call_later(1, self.tick)
where loop is the asyncio event loop variable you create earlier in:
loop = asyncio.get_event_loop()
Upvotes: 3