0

I am using the threading.Timer class in Python 3.9.x to repeatedly make an HTTP GET call every 60 seconds. What I am noticing is that the Timer class starts to lag behind system time after one or two attempts. Initially it lags behind 1 second and then slowly the lag increases and goes up to 5 minutes and more.

Is it because internally the timer is being restarted only when the called function has finished or some other reason?

I took this code from one of the SO question. I have also tried creating my own timer using divmod() and infinite loop etc but in my custom code also the lagging behaviour is same. In my custom code I even tried to invoke target own another separate thread. But nothing is helping.

Much appreciate some guidance here.

from threading import Timer

class AntianTimer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)
  • All the 'timer' does is wit a fixed amount of time from the moment it runs. There is no guarantee that `self.function()` won't take longer than a fraction of a second. – Martijn Pieters Aug 21 '21 at 17:04
  • If you must have a more precise timer, calculate how long it needs to wait until the next full minute has passed, than wait *that amount*. – Martijn Pieters Aug 21 '21 at 17:04

0 Answers0