Python Scheduler vs loop + sleep

2019-02-18 15:40发布

问题:

the following is:

python sched:

from time import time, sleep
from sched import scheduler

def daemon(local_handler):
    print 'hi'
    local_handler.enter(3, 1, daemon, (local_handler,))

if __name__ == '__main__':
    handler = scheduler(time, sleep)
    handler.enter(0, 1, daemon, (handler,))
    handler.run()

python loop + sleep:

from time import sleep

while True:
    print 'hello'
    sleep(3)

What is the difference between sched and loop+sleep, and sched will stop when the system time is changed?

回答1:

The difference between the two is that scheduler is more pythonic than loop + sleep for two reasons: elegance and modularity.

Long loops easily become difficult to read and require a lot more code to be written within. However, with a scheduler, a specific function can be called on a delay, containing all of the code within. This makes code much more readable and allows for moving code into classes and modules to be called within the main loop.

Python knows what the current time is by checking the local system. If the local system's time is changed, then that will affect a currently running program or script.



回答2:

Becaused the python sched is use system time for next iteration. The sleep is use cpu time clock for next iteration.



回答3:

A big difference is that the delay between multiple tasks is calculated as necessary. That means your loop will take:

  • time it needs to print("hello") or do the task that you need to do
  • time it takes to sleep(3)

while if you change the order in your scheduler to:

local_handler.enter(3, 1, daemon, (local_handler,))
do_the_task

your next task will be run either after 3 seconds, or immediately after do_the_task if it took longer than 3 seconds.

So the decision really comes down to: do you want your task executed every X time units, or with X time units space between executions.

Assuming you're using the typical (time, sleep) parameters, if the system time is changed, you'll get the next task run after the expected amount of time (sleep takes care of this, unless some signals were received in the meantime), but your next scheduled task time will be shifted. I believe that the next execution time will not be what you'd normally expect.