title: timer interrupt thread python
body: <p>I've been trying to make a precise timer in python, or as precise a OS allows it to be. But It seems to be more complicated than I initially thought.</p>
  <p>This is how I would like it to work:</p>
  <pre><code>from time import sleep
  from threading import Timer
  
  def do_this():
      print (&quot;hello, world&quot;)
  
  
  t = Timer(4, do_this)
  t.start()
  sleep(20)
  t.cancel()
  </code></pre>
  <p>Where during 20 seconds I would execute 'do_this' every fourth second. However 'do_this' executes once then the script terminates after 20 seconds.</p>
  <p>Another way would be to create a thread with a while loop.</p>
  <pre><code>import time
  import threading
  import datetime
  
  shutdown_event = threading.Event()
  
  def dowork():
      while not shutdown_event.is_set():
          print(datetime.datetime.now())
          time.sleep(1.0)
  
  def main():
  
      t = threading.Thread(target=dowork, args=(), name='worker')
      t.start()
  
      print(&quot;Instance started&quot;)
  
      try:
          while t.isAlive():
              t.join(timeout=1.0)
      except (KeyboardInterrupt, SystemExit):
              shutdown_event.set()
      pass
  
  if __name__ == '__main__':
      main()
  </code></pre>
  <p>This thread executes as expected but I get a timing drift. In this case have to compensate for the time it takes to execute the code in the while loop by adjusting the sleep accordingly.</p>
  <p>Is there a simple way in python to execute a timer every second (or any interval) without introducing a drift compared to the system time without having to compensate the sleep(n) parameter?</p>
  <p>Thanks for helping,</p>
  <p>/Anders</p>