""" signal.py An example of a python program that stops after a given time. See https://docs.python.org/2/library/signal.html Tested with python 2. Jim Mahoney | Apr 18 2018 | MIT License | cs.marlboro.college """ import signal, time class TimeHasRunOut(Exception): """ The exception raised when the timer expires """ # This is a user defined exception. # Python exceptions are used in try/except clauses # to handle errors or other events that change the # regular flow of program execution. pass def raise_TimeHasRunOut(signal_number, frame): """ signal handler - when the alarm goes out, raise an exception """ raise TimeHasRunOut() def start_alarm(time_in_sec): """ Start the alarm timer """ # The approach here is to use the operating system's built-in signaling # mechanism. Any process can be sent a signal, and can have a function # defined to run when it gets a signal. Signals are things like "quit", # which is what happens when you type control-C at a prompt. # When this process gets an ALARM signal, run raise_TimeHasRunOut(s,f) signal.signal(signal.SIGALRM, raise_TimeHasRunOut) # Tell the system to send this process an ALARM in this many seconds. signal.setitimer(signal.ITIMER_REAL, time_in_sec) def main(): print "signal.py - an example of a signal interrupting a process." start_alarm(5.0) # Set an alarm to go off in 5 sec. try: # Do this until an exception is raised. for i in range(100): print i time.sleep(0.5) except TimeHasRunOut: # Handle this sort of exception here. print "The alarm has gone off." main()