在一段时间后执行功能

时间:2020-06-22 04:12:06

标签: python python-3.x discord.py

我正在构建一个带有discordpy的discord机器人,并且我希望每十分钟执行一次函数(对于迷你游戏),但是如果我使用time.sleep,则整个程序将冻结并等待该时间,从而渲染我的bot完全没用,因为time.sleep会阻止程序执行。 discordpy还可以与异步函数和事件一起使用,因此很难找到放置while循环的位置。是否有一个模块可以每隔十分钟执行一次功能而不会停止我的机器人程序?

编辑: 与discordpy一起,您定义了所有异步函数,因此:

@client.event
async def on_message(message):
    # Code

然后在文件末尾写: client.run() 我的意思是,由于我需要到达那条线,所以我不能使用无限的while循环,没有那条线,机器人将毫无用处,所以我的问题是,我可以将“计时器”附加到脚本中吗这样每隔十分钟我可以执行一个功能?

4 个答案:

答案 0 :(得分:1)

为此您使用计划

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)

答案 1 :(得分:0)

告诉我您对此的看法。如果它不适用于您的代码,那么我可以对其进行调整:

import time
starttime=time.time()
def thing():
  print('hi')
while True:
  thing()
  time.sleep(60.0 - ((time.time() - starttime) % 60.0))

它处于while循环中,所以我不知道它与您的代码的配合情况如何,但是由于它是可以多次运行的机器人,因此可能会起作用。当然,例如,如果您希望它仅运行5次,则可以只对range(5)中的i表示: 希望这会有所帮助!

答案 2 :(得分:0)

尝试这样的事情,

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..

答案 3 :(得分:0)

Discord.py是使用python asyncio模块构建的。要在asyncio中休眠当前任务,您需要在asyncio.sleep()上等待,请注意,这不会阻塞线程或事件循环,而这正是您应该使用的。

import asyncio #Top of your file
...

await asyncio.sleep(10) #Doesn't blocks the rest of the program!

不建议在异步程序中创建NAGA RAJ S答案中提到的线程,这会浪费资源。

关于asyncio.sleep v / s time.sleep的更多信息:Python 3.7 - asyncio.sleep() and time.sleep()