Search code examples
pythonschedulerpython-multithreadingpython-sched

Scheduler with blocking=False


The Python scheduler works well with default value 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')

but I can't make it work with blocking=False.

Indeed with:

s.run(block=False)  
print('finished')  

the script stops immediately so obviously it does not work (this is normal behaviour). But with:

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

it does not work either: the tasks are strangely not executed.

I don't really understand the documentation:

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

How to use scheduler in blocking=False mode?


Solution

  • I found the solution: the blocking=False mode allows to do other things in the meantime and poll the new events every now and then. This works:

    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')