我正在构建一个带有discordpy的不和谐机器人,我希望每十分钟执行一次函数(对于小游戏),但是如果我使用time.sleep,整个程序将冻结并等待这段时间,使我的机器人完全无用,因为time.sleep会阻止程序执行。另外,discordpy适用于异步函数和事件,因此尝试找到放置while循环的位置是非常困难的。有没有一个模块可以让我每隔十分钟执行一次函数,而不会停止我的机器人的流程?
编辑:使用discordpy,您可以定义所有的异步函数,如下所示:
@client.event
async def on_message(message):
# Code然后在文件的末尾你写道:client.run()我想说的是,我不能使用无限的while循环,因为我需要到达那一行,没有这行机器人将是无用的,那么我的问题是,我能不能给我的脚本“附加”一个计时器,这样我就可以每隔十分钟执行一个函数?
发布于 2020-06-22 12:26:06
为此,您可以使用调度
import sched, time
sch = sched.scheduler(time.time, time.sleep)
def run_sch(do):
print("running at 10 mins")
# do your stuff
sch.enter(600, 1, run_sch, (do,))
sch.enter(600, 1, run_sch, (s,))
sch.run()或者您可以尝试以线程方式每隔10分钟运行一次特定的函数
import threading
def hello_world():
while True:
print("Hello, World!")
time.sleep(600)
t1 = threading.Thread(target=hello_world)
t1.start()
while True:
print('in loop')
time.sleep(1)发布于 2020-06-22 12:25:23
告诉我你对此的看法。如果它不能与您的代码一起工作,那么我可以调整它:
import time
starttime=time.time()
def thing():
print('hi')
while True:
thing()
time.sleep(60.0 - ((time.time() - starttime) % 60.0))它在while循环中,所以我不知道它在你的代码中会有多好的效果,但因为它是一个多次运行的机器人,所以它可能会工作。当然,如果您希望它只运行5次,例如,您可以只说for i in range(5):希望这会有帮助!
发布于 2020-06-22 12:28:33
试试这样的东西,
import schedule
def worker():
print("Executing...")
schedule.every(10).minutes.do(worker)
while True:
schedule.run_pending()
time.sleep(1)此外,我们还可以使用不同的包来实现此功能。
import sched
sched.scheduler(params)Threading along with sleep.
Use of Twisted package etc..https://stackoverflow.com/questions/62507316
复制相似问题