I'm looking for something similar to Python decorator for debouncing including function arguments , except with asyncio coroutines.
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. 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).
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.
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.
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. 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).
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.
I'm looking for a more elegant solution, hopefully that'll let me do something like:
@debounce(300)
async def foo():
# Do work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.