python计时器之谜

python timer mystery

好吧,至少对我来说是一个谜。 考虑以下:

1
2
3
4
5
6
7
8
9
10
11
import time
import signal

def catcher(signum, _):
    print"beat!"

signal.signal(signal.SIGALRM, catcher)
signal.setitimer(signal.ITIMER_REAL, 2, 2)

while True:
    time.sleep(5)

按预期工作,即提供"节拍!" 消息每2秒。 接下来,没有产生输出:

1
2
3
4
5
6
7
8
9
10
11
import time
import signal

def catcher(signum, _):
    print"beat!"

signal.signal(signal.SIGVTALRM, catcher)
signal.setitimer(signal.ITIMER_VIRTUAL, 2, 2)

while True:
    time.sleep(5)

问题在哪里?


从我的系统的man setitimer(强调我的):

The system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts.

ITIMER_REAL decrements in real time, and delivers SIGALRM upon expiration.

ITIMER_VIRTUAL decrements only when the process is executing, and delivers SIGVTALRM upon expiration.

您是否只是想念您的过程在睡觉时没有执行? 你需要花费很长时间才能在这个循环中累积实际使用的时间。


signal.ITIMER_VIRTUAL仅在进程正在运行时倒计时。 time.sleep(5)暂停进程,以便计时器不会减少。