Python调度程序可以很好地处理默认值blocking=True。
import sched, time
def print_time(a):
print("From print_time", time.time(), a)
s = sched.scheduler()
s.enter(2, priority=1, action=print_time, argument=(1,))
s.enter(2, priority=2, action=print_time, argument=(2,))
print(time.time())
s.run() # blocks until the last scheduled task is finished
print('finished')但我不能让它与blocking=False一起工作。
确实有:
s.run(block=False)
print('finished') 脚本立即停止,很明显它不工作(这是正常的行为)。但有:
s.run(block=False)
time.sleep(10) # sleeping to make sure the script does not terminate immediately,
print('finished') # but in real situation, there would be other tasks here它也不起作用:奇怪的是,任务没有执行。
我不太理解这些文档:
如果阻塞为false,则
执行预定的事件(如果有的话),然后返回调度器中下一个预定调用的截止日期(如果有的话)。
如何在blocking=False 模式下使用调度器?
发布于 2020-05-31 20:08:36
我找到了解决方案:blocking=False模式允许同时做其他事情,并不时轮询新事件。这样做是可行的:
import sched, time
def print_time(a):
print("From print_time", time.time(), a)
s = sched.scheduler()
s.enter(2, priority=1, action=print_time, argument=(1,))
s.enter(2, priority=2, action=print_time, argument=(2,))
for _ in range(50):
s.run(blocking=False)
time.sleep(0.1) # in a real situation, this would be some other tasks
print('finished')https://stackoverflow.com/questions/62116900
复制相似问题