Skip to main content
 首页 » 编程设计

Python 理解调度器

2025年05月04日12zhoujg

我有一个 python 调度程序 代码来打印 Hello 和 World!。

import sched 
import time 
 
def x(): 
    print "Hello" 
 
s = sched.scheduler(time.time, time.sleep) 
s.enter(10, 1, x, ()) 
s.run() 
print "World!" 

这将等待 10 秒 并输出:

Hello 
World! 

我认为调度器的工作是在不中断当前进程的情况下调度任务。但在这里它让整个程序进入休眠状态,其行为就像下面的代码一样:

import time 
 
def x(): 
    print "Hello" 
 
time.sleep(10) 
x() 
print "World!" 

我猜调度器让程序休眠是由于 sched.scheduler(time.time, time.sleep) 中的 time.sleep 参数。 无论如何我们可以让它像实时调度程序一样工作而不阻塞主进程而不使用任何 multithreading 或 multiprocessing 吗?

请您参考如下方法:

来自 the docs :

In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.

from threading import Timer 
 
def x(): 
    print "Hello" 
 
Timer(10, x, ()).start() 
print "World!" 

without blocking the main process without using any multithreading or multiprocessing

一个线程不能同时做两件事,所以... threading 是您为了不阻塞而需要使用的绝对最小值。