timer_demo.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- Mode: Python; tab-width: 4 -*-
  2. #
  3. # This module, and the timer.pyd core timer support, were written by
  4. # Sam Rushing (rushing@nightmare.com)
  5. import timer
  6. import time
  7. # Timers are based on Windows messages. So we need
  8. # to do the event-loop thing!
  9. import win32event, win32gui
  10. # glork holds a simple counter for us.
  11. class glork:
  12. def __init__ (self, delay=1000, max=10):
  13. self.x = 0
  14. self.max = max
  15. self.id = timer.set_timer (delay, self.increment)
  16. # Could use the threading module, but this is
  17. # a win32 extension test after all! :-)
  18. self.event = win32event.CreateEvent(None, 0, 0, None)
  19. def increment (self, id, time):
  20. print('x = %d' % self.x)
  21. self.x = self.x + 1
  22. # if we've reached the max count,
  23. # kill off the timer.
  24. if self.x > self.max:
  25. # we could have used 'self.id' here, too
  26. timer.kill_timer (id)
  27. win32event.SetEvent(self.event)
  28. # create a counter that will count from '1' thru '10', incrementing
  29. # once a second, and then stop.
  30. def demo (delay=1000, stop=10):
  31. g = glork(delay, stop)
  32. # Timers are message based - so we need
  33. # To run a message loop while waiting for our timers
  34. # to expire.
  35. start_time = time.time()
  36. while 1:
  37. # We can't simply give a timeout of 30 seconds, as
  38. # we may continouusly be recieving other input messages,
  39. # and therefore never expire.
  40. rc = win32event.MsgWaitForMultipleObjects(
  41. (g.event,), # list of objects
  42. 0, # wait all
  43. 500, # timeout
  44. win32event.QS_ALLEVENTS, # type of input
  45. )
  46. if rc == win32event.WAIT_OBJECT_0:
  47. # Event signalled.
  48. break
  49. elif rc == win32event.WAIT_OBJECT_0+1:
  50. # Message waiting.
  51. if win32gui.PumpWaitingMessages():
  52. raise RuntimeError("We got an unexpected WM_QUIT message!")
  53. else:
  54. # This wait timed-out.
  55. if time.time()-start_time > 30:
  56. raise RuntimeError("We timed out waiting for the timers to expire!")
  57. if __name__=='__main__':
  58. demo()