尝试使用任务有条件地安排消息发送-我目前有一个24小时循环任务,我想在参数化时间有条件地创建/触发一个单独的任务。
不确定是否可能单独使用任务,看到一些使用cron/一些cron库的建议,但好奇是否有比我一直在尝试的更好的方法。我考虑过如果满足条件,可能使用change_interval
方法来调整当前循环以在新的时间再次运行(并再次使用该方法将其更改为正常的24小时循环),但如果有更好的方法,这感觉像是一个janky解决方案。
我尝试了一个方法,当调用时,基本上会创建一个新任务,但是我可以看到,如果tasks
包装器在方法内的行为不像我期望的那样,这将无法工作-请注意,此代码似乎不工作
def schedule_alert(new_time):
@tasks.loop(time=new_time, count=1)
def alert():
...
@tasks.loop(hours=24, time=notification_time)
def daily_method():
new_time = some_code()
if new_time:
# if this condition is met, I want to schedule a new task at the new_time
schedule_alert(new_time)
由于只需要运行一次,因此不需要为此使用循环。您可以简单地创建一个在给定时间之前一直休眠的函数。例如:
async def alert(alert_time):
await discord.utils.sleep_until(alert_time)
# do something
...
@tasks.loop(hours=24)
async def daily_method():
new_time = some_code()
if new_time:
asyncio.create_task(alert(new_time))
自discord.py 2.0.0以来,我们可以使用tasks.loop
装饰器和time
参数来调度任务:
from discord.ext import tasks
from datetime import datetime
# year, month, day, hour, minute
run_at = datetime(2023, 3, 7, 12, 0)
@tasks.loop(hours=24, time=run_at)
async def my_task():
print("I run everyday at 12:00")
my_task.start()