DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Python Watchdog Timer

08.09.2009
| 13287 views |
  • submit to reddit
        Easily interrupt long portions of code if they take too long to run.

#!/usr/bin/python
# file: watchdog.py
# license: MIT License

import signal

class Watchdog(Exception):
  def __init__(self, time=5):
    self.time = time
  
  def __enter__(self):
    signal.signal(signal.SIGALRM, self.handler)
    signal.alarm(self.time)
  
  def __exit__(self, type, value, traceback):
    signal.alarm(0)
    
  def handler(self, signum, frame):
    raise self
  
  def __str__(self):
    return "The code you executed took more than %ds to complete" % self.time

Example:

#!/usr/bin/python

# import the class
from watchdog import Watchdog

# don't allow long_function to take more than 5 seconds to complete
try:
  with Watchdog(5):
    long_function()
except Watchdog:
  print "long_function() took too long to complete"