all Python 3Linux · macOSsignalfunction
signal.setitimer()
timers
Starts an interval timer with microsecond resolution, one-shot or repeating. Unix only (Linux, macOS).
Syntax
signal.setitimer(which, seconds, interval=0.0)
ITIMER_REAL sends SIGALRM and shares it with alarm — they disrupt each other. ITIMER_VIRTUAL and ITIMER_PROF count CPU time, not wall time: they stand still during sleep. A non-zero interval repeats the signal forever, so clearing the timer with setitimer(which, 0) is mandatory. A negative time raises signal.ItimerError, a subclass of OSError.
Examples
import signal, time
ticks = []
old = signal.signal(signal.SIGALRM, lambda s, f: ticks.append(s))
signal.setitimer(signal.ITIMER_REAL, 0.01, 0.01) # каждые 10 мс
try:
while len(ticks) < 3:
time.sleep(0.005)
finally:
signal.setitimer(signal.ITIMER_REAL, 0) # снять обязательно
signal.signal(signal.SIGALRM, old)
print(len(ticks)) # → 3
import signal
try:
signal.setitimer(signal.ITIMER_REAL, -1)
except OSError as e:
print(isinstance(e, signal.ItimerError)) # → True
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy