multithreading - timer interrupt thread python -


i've been trying make precise timer in python, or precise os allows be. seams more complicated thought.

this how work:

from time import sleep threading import timer  def do_this():     print ("hello, world")   t = timer(4, do_this) t.start() sleep(20) t.cancel() 

where during 20 seconds execute 'do_this' every fourth second. 'do_this' executes once script terminates after 20 seconds.

another way create thred while loop.

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("instance started")      try:         while t.isalive():             t.join(timeout=1.0)     except (keyboardinterrupt, systemexit):             shutdown_event.set()     pass  if __name__ == '__main__':     main() 

this thread executes expected timing drift. in case have compensate time takes execute code in while loop adjusting sleep accordingly.

is there simple way in python execute timer every second (or interval) without introducing drift compared system time without having compensate sleep(n) parameter?

thanks helping,

/anders

if dowork() runs in less time intervals, can spawn new thread every 4 seconds in loop:

def dowork():   wlen = random.random()   sleep(wlen) # emulate doing work   print 'work done in %0.2f seconds' % wlen  def main():   while 1:     t = threading.thread(target=dowork)     time.sleep(4) 

if dowork() potentially run more 4 seconds, in main loop want make sure previous job finished before spawning new one.

however, time.sleep() can drift because no guarantees made on how long thread suspended. correct way of doing figure out how long job took , sleep remaining of interval. think how ui , game rendering engines work, have display fixed number of frames per second @ fixed times , rendering each frame take different length of time complete.


Comments