Discord.py Bot 在每天的特定时间运行函数

Mar*_*nto 8 python scheduler heroku discord.py

我正在使用discord.py 创建一个discord 机器人,我需要每天在特定时间执行某些操作。我看到这个答案:如何在discord.py重写中进行循环?到目前为止我一直在使用它。

当我在 heroku 免费计划上托管我的机器人时,问题就开始了。Heroku 上的服务器每天至少重置一次,这会弄乱计时器,如该帖子所示。

我还看到了时间表库。问题在于它似乎使用了无限循环。这不会阻止我在 24 小时内运行其他任何操作吗?除了每 24 小时发送一次消息之外,机器人还需要能够随时响应命令。

即使服务器重置,如何每天在特定时间执行操作?先感谢您!

omn*_*n_1 8

您可以编写一个函数在不同的线程上定期运行,并检查是否是发送消息的正确时间,如下例所示:

from datetime import datetime
import threading


def checkTime():
    # This function runs periodically every 1 second
    threading.Timer(1, checkTime).start()

    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)

    if(current_time == '02:11:00'):  # check if matches with the desired time
        print('sending message')


checkTime()
Run Code Online (Sandbox Code Playgroud)


act*_*ger 1

您是否考虑过使用多线程来运行您的程序?您可以让一个线程等待您想要的时间,而另一个线程则运行程序的其余部分。以下是一些可帮助您入门的文档:Python 线程简介线程文档