Reputation: 455
I would like a my Python script to receive a periodic alarm say every 5 seconds. I have tried the following code, but it only receive the alarm once then hangs.
import os
import signal
import time
def handler(signum, stack):
print 'Alarm: ', time.ctime()
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
Upvotes: 1
Views: 7801
Reputation: 1
Because alarm is set once only. If you need periodic
Try this:
def handler(signum, stack):
print 'Alarm: ', time.ctime()
signal.alarm(5)
Upvotes: 0
Reputation: 4177
Nothing hangs, nothing receives the alarm once. Your program is already dead when the alarm bell rings the first time. Try so:
import signal
import time
def handler(signum, stack):
print 'Alarm: ', time.ctime()
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
time.sleep(10)
print "interrupted"
When you want it in a loop, just wrap it in a loop:
signal.signal(signal.SIGALRM, handler)
for i in range(1000):
signal.alarm(5)
time.sleep(10)
print "interrupted #%d" % i
You can also do infinite loop. But catch KeyboardInterrupt
in this case to avoid nasty exceptions like
Alarm: Sat Mar 19 08:28:06 2016
interrupted #2
^CTraceback (most recent call last):
File "alaam.py", line 10, in <module>
time.sleep(10)
KeyboardInterrupt
Upvotes: 3