blocking=False 的调度器
Scheduler with blocking=False
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
也不行:奇怪的是任务没有执行。
我不太理解文档:
If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any).
如何在blocking=False
模式下使用调度器?
我找到了解决方案: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')
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
也不行:奇怪的是任务没有执行。
我不太理解文档:
If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any).
如何在blocking=False
模式下使用调度器?
我找到了解决方案: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')