Skip to content Skip to sidebar Skip to footer

Timer Interrupt Thread Python

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. This is how I would like it to

Solution 1:

If dowork() always runs in less time than your intervals, you can spawn a new thread every 4 seconds in a loop:

defdowork():
  wlen = random.random()
  sleep(wlen) # Emulate doing some workprint'work done in %0.2f seconds' % wlen

defmain():
  while1:
    t = threading.Thread(target=dowork)
    time.sleep(4)

If dowork() could potentially run for more than 4 seconds, then in your main loop you want to make sure the previous job is finished before spawning a new one.

However, time.sleep() can itself drift because no guarantees are made on how long the thread will actually be suspended. The correct way of doing it would be to figure out how long the job took and sleep for the remaining of the interval. I think this is how UI and game rendering engines work, where they have to display fixed number of frames per second at fixed times and rendering each frame could take different length of time to complete.

Post a Comment for "Timer Interrupt Thread Python"