Over a million developers have joined DZone.

Simple Python Watchdog Timer

·
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"

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}