I am starting to learn Python (newbie), so not much idea about the different modules etc.
Scenario that I want to simulate:
I have a program prg1.py
that I want to run for some user defined time say t
seconds. After this time (t
seconds), the program should exit. For this I am using signal.signal()
to create alarm. Below is the working code:
import signal import time import sys def receive_alarm(signum, stack): sys.exit('Exiting!') signal.signal(signal.SIGALRM, receive_alarm) signal.alarm(10) while 1: print 'Working...' time.sleep(1)
The program runs for 10 seconds and then exits as expected.
Note: The while loop below is just for testing, it would be replaced by my working code.
Now I want to implement multiple signals to do different tasks at different intervals of time.
e.g. In EVERY
:
5
seconds: execute a specific function fun1()
10
seconds: execute a specific function fun2()
, and so on... (tasks I want to perform in the program)
I tried adding another alarm as shown below, but didn't work:
import signal
import time
import sys
def receive_alarm(signum, stack):
sys.exit('Exiting!')
def receive_alarm_two(signup, stack):
print 'Call to other functions!'
signal.signal(signal.SIGALRM, receive_alarm)
signal.alarm(10)
# Second Alarm
signal.signal(signal.SIGALRM, receive_alarm_two)
signal.alarm(2)
while 1:
print 'Working...'
time.sleep(1)
This doesn't work! Simple exits without any error or exit message :(
How can this functionality be implemented?
NOTE: Use of Threads is restricted.
NOTE: As I want the program to keep listening to different signals, it can't sleep i.e. cannot use time.sleep().