settimeout in python code example

Example 1: python timeout

You may use the signal package if you are running on UNIX:

import signal

# Register an handler for the timeout
def handler(signum, frame):
  print("Forever is over!")
       raise Exception("end of time")
   

# This function *may* run for an indetermined time...
def loop_forever():
     import time
     while 1:
         print("sec")
         time.sleep(1)
         
         

# Register the signal function handler
signal.signal(signal.SIGALRM, handler)


# Define a timeout for your function
signal.alarm(10)
0

try:
    loop_forever()
except Exception, exc:
    print(exc)

Example 2: python version of settimout

from datetime import datetime, timedelta
import heapq

# just holds a function, its arguments, and when we want it to execute.
class TimeoutFunction:
    def __init__(self, function, timeout, *args):
        self.function = function
        self.args = args
        self.startTime = datetime.now() + timedelta(0,0,0,timeout) 

    def execute(self):
        self.function(*self.args)

# A "todo" list for all the TimeoutFunctions we want to execute in the future
# They are sorted in the order they should be executed, thanks to heapq
class TodoList: 
    def __init__(self):
        self.todo = []

    def addToList(self, tFunction):
        heapq.heappush(self.todo, (tFunction.startTime, tFunction))

    def executeReadyFunctions(self):
        if len(self.todo) > 0:
            tFunction = heapq.heappop(self.todo)[1]
            while tFunction and datetime.now() > tFunction.startTime:
                #execute all the functions that are ready
                tFunction.execute()
                if len(self.todo) > 0:
                    tFunction = heapq.heappop(self.todo)[1]
                else:
                    tFunction = None                    
            if tFunction:
                #this one's not ready yet, push it back on
                heapq.heappush(self.todo, (tFunction.startTime, tFunction))

def singleArgFunction(x):
    print str(x)

def multiArgFunction(x, y):
    #Demonstration of passing multiple-argument functions
    print str(x*y)

# Make some TimeoutFunction objects
# timeout is in milliseconds
a = TimeoutFunction(singleArgFunction, 1000, 20)
b = TimeoutFunction(multiArgFunction, 2000, *(11,12))
c = TimeoutFunction(quit, 3000, None)

todoList = TodoList()
todoList.addToList(a)
todoList.addToList(b)
todoList.addToList(c)

while True:
    todoList.executeReadyFunctions()