简体   繁体   English

去抖 python asyncio 协程

[英]Debounce python asyncio coroutine

I'm looking for something similar to Python decorator for debouncing including function arguments , except with asyncio coroutines.我正在寻找类似于Python 装饰器的东西, 用于去抖动包括函数参数,除了 asyncio 协程。

The background here is that I'm working on a discord bot with discord.py, and there's a computationally intensive coroutine that I would like to run after every command to the bot.这里的背景是我正在使用 discord.py 开发一个不和谐的机器人,并且有一个计算密集型协程,我想在对机器人发出每个命令后运行它。 But due to the cost I want to debounce it, since if there's a new command coming in it'll just invalidate the work anyways (think lots of IO and number crunching).但是由于成本,我想消除它,因为如果有一个新命令进来,它无论如何都会使工作无效(想想很多 IO 和数字运算)。

So far the ugly solution I've come up with is:到目前为止,我想出的丑陋的解决方案是:

# Function to be debounced
async def foo():
    asyncio.sleep(300)
    task = None
    res = await do_work()
    await send_result(res)

task = None

async def after_command():
    if task:
        task.cancel()
    task = bot.loop.create_task(foo())

In other words, just cancel the task every time and re-schedule it 5 minutes in the future.换句话说,只需每次取消任务并在未来 5 分钟重新安排它。

I'm looking for a more elegant solution, hopefully that'll let me do something like:我正在寻找一个更优雅的解决方案,希望这能让我做类似的事情:

@debounce(300)
async def foo():
    # Do work

I'm looking for something similar to Python decorator for debouncing including function arguments , except with asyncio coroutines.我正在寻找类似于Python 装饰器的东西, 用于去抖动包括函数参数,除了 asyncio 协程。

The background here is that I'm working on a discord bot with discord.py, and there's a computationally intensive coroutine that I would like to run after every command to the bot.这里的背景是我正在使用 discord.py 开发一个不和谐的机器人,并且有一个计算密集型协程,我想在对机器人发出每个命令后运行它。 But due to the cost I want to debounce it, since if there's a new command coming in it'll just invalidate the work anyways (think lots of IO and number crunching).但是由于成本,我想消除它,因为如果有一个新命令进来,它无论如何都会使工作无效(想想很多 IO 和数字运算)。

So far the ugly solution I've come up with is:到目前为止,我想出的丑陋的解决方案是:

# Function to be debounced
async def foo():
    asyncio.sleep(300)
    task = None
    res = await do_work()
    await send_result(res)

task = None

async def after_command():
    if task:
        task.cancel()
    task = bot.loop.create_task(foo())

In other words, just cancel the task every time and re-schedule it 5 minutes in the future.换句话说,只需每次取消任务并在未来 5 分钟重新安排它。

I'm looking for a more elegant solution, hopefully that'll let me do something like:我正在寻找一个更优雅的解决方案,希望这能让我做类似的事情:

@debounce(300)
async def foo():
    # Do work

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM