Skip to content

Instantly share code, notes, and snippets.

@shyba
Last active December 30, 2022 19:09
Show Gist options
  • Save shyba/1a65c1eb74d41bed686a23e79995daa8 to your computer and use it in GitHub Desktop.
Save shyba/1a65c1eb74d41bed686a23e79995daa8 to your computer and use it in GitHub Desktop.
simple watchdog to detect reactor blocked periods
import time
import sys
import inspect
from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from twisted.internet.threads import deferToThread
from twisted.logger import textFileLogObserver
from twisted.python import log
log.addObserver(textFileLogObserver(sys.stdout))
class Watchdog:
def __init__(self, delay=0.01):
self.delay = delay
self.loop_call = LoopingCall.withCount(self.watch)
def start(self):
self.loop_call.start(self.delay)
def watch(self, count):
current = reactor.getDelayedCalls()
deferToThread(self._check, count, current)
def _check(self, count, current):
if count > 1:
print 'Reactor was blocked for %s seconds' % (count * self.delay)
for call in self.prev:
if call.called:
print call
print call.func
if call.func and 'function' in str(type(call.func)):
print inspect.getsourcefile(call.func)
print inspect.getsource(call.func)
self.prev = current
def stop(self):
return self.loop_call.stop()
def blockme():
time.sleep(0.5)
print 'Start!'
dog = Watchdog()
dog.start()
reactor.callLater(2, deferToThread, blockme)
reactor.callLater(3, blockme)
reactor.callLater(10, reactor.stop)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment