Python 调度程序 vs 循环 + 睡眠 [英] Python Scheduler vs loop + sleep

查看:82
本文介绍了Python 调度程序 vs 循环 + 睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是:

python 调度:

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 循环 + 睡眠:

from time import sleep

while True:
    print 'hello'
    sleep(3)

sched 和 loop+sleep 有什么区别,sched 会在系统时间改变时停止?

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

推荐答案

一个很大的区别是多个任务之间的延迟是根据需要计算的.这意味着您的循环将需要:

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

  • 时间需要print("hello")或完成你需要做的任务
  • sleep(3)
  • 所需的时间
  • 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

您的下一个任务将在 3 秒后运行,或者在 do_the_task 后立即运行(如果时间超过 3 秒).

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

所以决定实际上归结为:您希望任务每 X 时间单位执行一次,还是执行之间有 X 时间单位间隔.

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.

假设您正在使用典型的 (time, sleep) 参数,如果系统时间发生更改,您将在预期的时间后运行下一个任务 (sleep 会处理这个问题,除非在此期间收到了一些信号),但是您的下一个计划任务时间将被转移.我相信下一次执行时间不会是您通常所期望的.

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.

这篇关于Python 调度程序 vs 循环 + 睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆