I'd like to understand how to use the optional parameter blocking
in the method scheduler.run(blocking=True)
. Any practical/real-world example would be very helpful.
Based on the research I've done so far, the intention of the blocking
optional argument is for non-blocking or async applications[1][2]. Below is the main run loop of the schduler (from the python 3.6 library sched.py
). Following through the code, I notice that whenever blocking
is set to False
, immediately returns the time difference between target time and current time, unless the target time had passed, in which case the action would be executed.
while True:
with lock:
if not q:
break
time, priority, action, argument, kwargs = q[0]
now = timefunc()
if time > now:
delay = True
else:
delay = False
pop(q)
if delay:
if not blocking:
return time - now
delayfunc(time - now)
else:
action(*argument, **kwargs)
delayfunc(0) # Let other threads run
Seems to me the non-blocking design requires me to keep running the scheduler until the queue is clean. Thus, I'm thinking about maintaining a task queue myself and keep pushing the scheduler.run
task into the queue (like the code below.) Is this a desirable design? What is the proper way of using the non-blocking scheduler?
def action():
print('action at: ', datetime.now())
if __name__ == '__main__':
s = sched.scheduler(time.time)
target_time = datetime.now() + timedelta(seconds=5)
s.enterabs(target_time.timestamp(), 1, action)
run = functools.partial(s.run, blocking=False)
taskq = deque()
taskq.append(run)
while taskq:
task = taskq.popleft()
result = task()
print(result)
if result:
taskq.append(run)
time.sleep(1)
print('end tasks')
[2] Issue13449: sched - provide an "async" argument for run() method