【问题标题】:Scheduler with blocking=False阻塞 = False 的调度程序
【发布时间】:2020-05-31 13:23:39
【问题描述】:

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

它也不起作用:任务奇怪地没有执行。

我不太了解文档:

如果阻塞为假,则执行由于最快到期的计划事件(如果有),然后返回调度程序中下一个计划调用的截止日期(如果有)。

blocking=False模式下如何使用调度器?

【问题讨论】:

    标签: python scheduler python-multithreading python-sched


    【解决方案1】:

    我找到了解决方案: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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 2023-03-06
      • 2018-06-26
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多