Advertisement
Guest User

Untitled

a guest
Sep 29th, 2011
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #Based off of http://twistedmatrix.com/trac/browser/sandbox/exarkun/btt.py
  2.  
  3. import array, struct, signal, traceback, time, StringIO
  4.  
  5. from twisted.internet import task
  6. from twisted.python import log
  7.  
  8. if hasattr(signal, 'setitimer'):
  9. # Use the built in itimer if we are python 2.6 or greater
  10. def itimer(seconds):
  11. signal.setitimer(signal.ITIMER_REAL, seconds)
  12. else:
  13. try:
  14. # Then try py-itimer from http://www.cute.fi/~torppa/py-itimer/
  15. import itimer as py_itimer
  16. except ImportError:
  17. # Otherwise use the dl module
  18. import dl
  19. def itimer(seconds, libc=dl.open('libc.so.6')):
  20. sec = int(seconds)
  21. msec = int((seconds - sec) * 1e6)
  22. timeval = array.array('I', [0, 0, sec, msec])
  23. if libc.call('setitimer', 0, timeval.buffer_info()[0], 0) == -1:
  24. raise RuntimeError("Who knows what")
  25. else:
  26. # Hooray
  27. def itimer(seconds):
  28. py_itimer.setitimer(0, seconds, 0)
  29.  
  30. class BigTimesliceTimer(object):
  31. lc = None
  32. lastRan = None
  33. _stack = None
  34.  
  35. def start(self, precision=0.01):
  36. assert self.lc is None
  37. self.precision = precision
  38. signal.signal(signal.SIGALRM, self._signal)
  39. itimer(precision * 1.1)
  40. self.lc = task.LoopingCall(self._run)
  41. self.lc.start(precision).addErrback(self._ebLoop)
  42.  
  43.  
  44. def stop(self):
  45. self.lc.stop()
  46. del self.lc
  47.  
  48.  
  49. def _ebLoop(self, err):
  50. log.msg("BigTimesliceTimer broke")
  51. log.err(err)
  52.  
  53.  
  54. def _run(self):
  55. now = time.time()
  56. if self._stack is not None:
  57. print 'Reactor is stalled:'
  58. print self._stack
  59. self._stack = None
  60. self.lastRan = now
  61. signal.signal(signal.SIGALRM, self._signal)
  62. itimer(self.precision * 1.1)
  63.  
  64.  
  65. def _signal(self, signum, frame):
  66. s = StringIO.StringIO()
  67. traceback.print_stack(file=s)
  68. self._stack = '\n'.join(s.getvalue().splitlines()[:-2])
  69.  
  70. if __name__ == '__main__':
  71. #TEST
  72.  
  73. #import sys
  74. #log.startLogging(sys.stdout)
  75.  
  76. from twisted.internet import reactor
  77. BigTimesliceTimer().start(3)
  78.  
  79. # Block for 4 seconds after startup
  80. reactor.callWhenRunning(time.sleep, 4)
  81.  
  82. reactor.run()
  83.  
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement