Skip to content

Instantly share code, notes, and snippets.

@theduderog
Created December 10, 2010 00:12
Show Gist options
  • Save theduderog/735556 to your computer and use it in GitHub Desktop.
Save theduderog/735556 to your computer and use it in GitHub Desktop.
A decorator for adding timeouts to Deferred calls that don't offer an alternative
#
# This gist is released under Creative Commons Public Domain Dedication License CC0 1.0
# http://creativecommons.org/publicdomain/zero/1.0/
#
from twisted.internet import defer, reactor
class TimeoutError(Exception):
"""Raised when time expires in timeout decorator"""
def timeout(secs):
"""
Decorator to add timeout to Deferred calls
"""
def wrap(func):
@defer.inlineCallbacks
def _timeout(*args, **kwargs):
rawD = func(*args, **kwargs)
if not isinstance(rawD, defer.Deferred):
defer.returnValue(rawD)
timeoutD = defer.Deferred()
timesUp = reactor.callLater(secs, timeoutD.callback, None)
try:
rawResult, timeoutResult = yield defer.DeferredList([rawD, timeoutD], fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True)
except defer.FirstError, e:
#Only rawD should raise an exception
assert e.index == 0
timesUp.cancel()
e.subFailure.raiseException()
else:
#Timeout
if timeoutD.called:
rawD.cancel()
raise TimeoutError("%s secs have expired" % secs)
#No timeout
timesUp.cancel()
defer.returnValue(rawResult)
return _timeout
return wrap
@wywin2000
Copy link

Hi Roger,

Thanks a lot for your explanation.

Regards,
Yong

@htoothrot
Copy link

Roger, can you clarify the copyright/license for this code? Thanks.

@theduderog
Copy link
Author

It's public domain. I do not wish to retain any copyrights. What's the best way to indicate that?

@htoothrot
Copy link

Roger,

CC0 is intended to allow one to place a work as nearly as possible into the public domain, worldwide. I believe that it would be sufficient to add a comment along the lines of:

"This gist is released under the Creative Commons 0 license. See http://creativecommons.org/publicdomain/zero/1.0/ for more information"

I appreciate it.

@theduderog
Copy link
Author

Thanks @htoothrot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment