我如何 运行 class 中的异步方法与 asyncio.create_server 一起使用?

How do I run an method async inside a class that is being used with asyncio.create_server?

我正在使用带有 asyncio 的高速公路,我正在尝试在 class 中创建一个方法,每隔 x 秒扩展一次 WebSocketServerFactory 运行。

高速公路网站上的文档是这样做的:

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)

我只是将 WebSocketServerFactory class 替换为扩展它的 class,并且我想 运行 每 x 秒在其中添加一个方法。

我在 autobahn 网站上找到了一个这样的例子,但它使用的是 twisted 而不是 asyncio。

这是我想要的一个简短的例子(original and full version),但是这个例子使用了扭曲:

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)

如何使用 asyncio 实现相同的目的?

根据您的示例,可以使用 asyncio 事件循环完成与 asyncio 相同的功能:Asyncio delayed calls.

所以在你的例子中,这意味着这样的事情:

def tick(self):
    print("tick!")
    self.do_something()
    loop.call_later(1, self.tick)

其中 loop 是您之前创建的 asyncio 事件循环变量:

loop = asyncio.get_event_loop()