Python - 带有asyncio/coroutine的计时器

Gre*_*ler 5 python timer nonblocking python-asyncio

我试图设置一个计时器,它将中断正在运行的进程并在它触发时调用一个协同程序.但是,我不确定实现这一目标的正确方法是什么.我找到了AbstractEventLoop.call_later,以及threading.Timer,但这些似乎都不起作用(或者我使用它们不正确).代码非常基本,看起来像这样:

def set_timer( time ):
    self.timer = Timer( 10.0, timeout )
    self.timer.start()
    #v2
    #self.timer = get_event_loop()
    #self.timer.call_later( 10.0, timeout )
    return

async def timeout():
    await some_func()
    return
Run Code Online (Sandbox Code Playgroud)

设置非阻塞计时器的正确方法是什么,在几秒钟后调用回调函数?能够取消计时器将是一个奖励,但不是一个要求.我需要的主要事情是:非阻塞并成功调用协同例程.现在它返回一个错误,该对象无法等待(如果我抛出await)或some_func从未等待过,并且预期的输出永远不会发生.

Mik*_*mov 8

使用ensure_future创建任务是在不阻止执行流程的情况下启动某些作业的常用方法.您也可以取消任务.

我为您编写了示例实现,以便从中开始:

import asyncio


class Timer:
    def __init__(self, timeout, callback):
        self._timeout = timeout
        self._callback = callback
        self._task = asyncio.ensure_future(self._job())

    async def _job(self):
        await asyncio.sleep(self._timeout)
        await self._callback()

    def cancel(self):
        self._task.cancel()


async def timeout_callback():
    await asyncio.sleep(0.1)
    print('echo!')


async def main():
    print('\nfirst example:')
    timer = Timer(2, timeout_callback)  # set timer for two seconds
    await asyncio.sleep(2.5)  # wait to see timer works

    print('\nsecond example:')
    timer = Timer(2, timeout_callback)  # set timer for two seconds
    await asyncio.sleep(1)
    timer.cancel()  # cancel it
    await asyncio.sleep(1.5)  # and wait to see it won't call callback


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
Run Code Online (Sandbox Code Playgroud)

输出:

first example:
echo!

second example:
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用 `asyncio.create_task` 而不是 `asyncio.ensure_future` https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task (4认同)
  • @dowi 与“await”创建任务不同,允许某些作业“在后台”运行。如果你这样做 `timer = Timer(1, timeout_callback); wait some()`,那么“some”将立即启动,并可能在“timeout_callback”之前完成。如果你这样做 `await asyncio.sleep(1); 等待超时_回调();wait some()`,那么“some”将始终在“timeout_callback”之后启动并完成。请参阅此答案以获取更多信息:/sf/answers/2614189511/ (2认同)

Hel*_*org 7

感谢 Mikhail Gerasimov 的回答,这非常有用。这是对米哈伊尔的回答的扩展。这是一个有一些曲折的间隔计时器。也许它对某些用户有用。

import asyncio


class Timer:
    def __init__(self, interval, first_immediately, timer_name, context, callback):
        self._interval = interval
        self._first_immediately = first_immediately
        self._name = timer_name
        self._context = context
        self._callback = callback
        self._is_first_call = True
        self._ok = True
        self._task = asyncio.ensure_future(self._job())
        print(timer_name + " init done")

    async def _job(self):
        try:
            while self._ok:
                if not self._is_first_call or not self._first_immediately:
                    await asyncio.sleep(self._interval)
                await self._callback(self._name, self._context, self)
                self._is_first_call = False
        except Exception as ex:
            print(ex)

    def cancel(self):
        self._ok = False
        self._task.cancel()


async def some_callback(timer_name, context, timer):
    context['count'] += 1
    print('callback: ' + timer_name + ", count: " + str(context['count']))

    if timer_name == 'Timer 2' and context['count'] == 3:
        timer.cancel()
        print(timer_name + ": goodbye and thanks for all the fish")


timer1 = Timer(interval=1, first_immediately=True, timer_name="Timer 1", context={'count': 0}, callback=some_callback)
timer2 = Timer(interval=5, first_immediately=False, timer_name="Timer 2", context={'count': 0}, callback=some_callback)

try:
    loop = asyncio.get_event_loop()
    loop.run_forever()
except KeyboardInterrupt:
    timer1.cancel()
    timer2.cancel()
    print("clean up done")
Run Code Online (Sandbox Code Playgroud)

  • @rohitpal,你错了。计时器在其自己的异步任务中运行,任何其他任务将继续运行。大多数时候,计时器将在“asyncio.sleep()”中休眠,以允许其他任务运行。计时器回调是异步的。正如您所建议的那样,没有任何阻塞! (3认同)