好的,所以我正在研究一个调度程序,我在想类似 timeOut(3,print,'hello')的东西,它会每三秒打印一次 hello,我尝试了一些方法,但都失败了。此外,为此使用 time.sleep 也不太有效,因为我还需要运行除一个任务之外的其他任务
编辑:我找到了如何做我需要的事情,很抱歉感到困惑,但这为我需要的做了诀窍,感谢您回答大家。
class test:
def __init__(self):
self.objectives = set()
class Objective:
pass
def interval(self,timeout,function,*data):
newObjective = self.Objective()
newObjective.Class = self
newObjective.timeout = time.time()+timeout
newObjective.timer = timeout
newObjective.function = function
newObjective.repeate = True
newObjective.data = data
self.objectives.add(newObjective)
return True
def runObjectives(self):
timeNow = time.time()
for objective in self.objectives:
timeout = objective.timer
if objective.timeout <= timeNow:
objective.function(*objective.data)
if objective.repeate:
objective.timeout = timeNow + timeout
self.main()
else:
self.objectives.remove(objective)
print('removed')
def main(self):
while True:
self.runObjectives()
标准库包括一个名为 sched
的用于调度的模块。它可以使用 delayfunc
构造函数参数适应在各种环境中工作。使用它,您的问题可能会显示为:
def event():
scheduler.enter(3, 0, event, ()) # reschedule
print('hello')
现在,这取决于您如何运行其他任务。是否在使用事件循环?它可能具有类似的调度机制(至少twisted
callLater
,GObject
有timeout_add
)。如果所有其他方法都失败了,您可以生成一个新线程并执行一个sched.scheduler
,其中包含time.sleep
。