简体   繁体   English

Python Asyncio 每周安排任务

[英]Python Asyncio schedule tasks weekly

I am writing a discord bot in Python, which already has the two async overwritten methods on_ready and on_message to react to messages in a certain way.我正在用 Python 编写一个不和谐的机器人,它已经有两个异步覆盖的方法 on_ready 和 on_message 以某种方式对消息做出反应。

Now I wanted to add a function, which should be called once in a week.现在我想添加一个函数,应该每周调用一次。 I tried something with asyncio.sleep() but I don't want to start the bot at that specific time and then sleep 604.800 sec (1 week in seconds) to repeat that function every week.我用 asyncio.sleep() 尝试了一些东西,但我不想在那个特定时间启动机器人然后睡眠 604.800 秒(1 周以秒为单位)每周重复该功能。

Here's what I got so far:这是我到目前为止所得到的:

class MyClient(discord.Client):

    async def on_ready(self):
        #some initial stuff
        self.loop.create_task(self.routine())

    async def on_message(self, message):
        #reply to chat messages
        await message.channel.send("Reply")

    async def routine(self):
        while True:
            print("I'm on that routine boi")
            await asyncio.sleep(3)

It works so far, that I can use the bot in discord and get the outputs every 3 seconds.到目前为止,它可以工作,我可以不和谐地使用机器人并每 3 秒获得一次输出。 But I'd prefer something like from the schedule module to use something like但我更喜欢从schedule 模块中使用类似的东西

scheduler.every().sunday.at("8:55").do(self.routine())

Any chance to do something similar in combination with asyncio?有机会结合 asyncio 做类似的事情吗?

The Event loop provides mechanisms to schedule callback functions to be called at some point in the future, as shown here in Python docs事件循环提供了安排回调函数在未来某个时间点调用的机制,如Python 文档中所示

class MyClient(discord.Client):

    async def on_ready(self):
        #some initial stuff
        self.loop.create_task(self.routine())

    async def on_message(self, message):
        #reply to chat messages
        await message.channel.send("Reply")

   async def execute():
         res = await loop.call_later(delay, callback, *args)
         delay += delay + 604800 
         return res



    async def routine(self):
        while True:
            print("I'm on that routine boi")
            res = await loop.run_until_complete(execute)

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

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