Home > other >  Run a function every 5 minutes starting from a particular wall clock time
Run a function every 5 minutes starting from a particular wall clock time

Time:08-09

I want to run a function every 5 minutes starting at a particular wall clock time.

I have implemeneted threading.timer which runs every 5 minutes (interval) but I don't know how to start this timer at a particular time.

from threading import Timer


class BSOJobScheduler(object):

    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.daemon = True
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

Please advise

CodePudding user response:

The easiest way to that is using Time.time() so I will use that.

You start timer like this: start = Time.time() And end like this: end = Time.time() Then to get value of time you will just subtract start from end like this: value = end - start You have to do like this becouse start = Time.time() gets value from computer so your next step is get another value from computer end = Time.time() and just subtract it.

And you just checking if value >= 300 (300secounds is 5minutes).

CodePudding user response:

One of the threads could do someting like this:

INTERVAL = 5 * 60

next_run = time.monotonic() # better than time.time()
while True:                 # or while not stop_condition:
    my_function()           # should not take more time than the INTERVAL
    next_run  = INTERVAL
    sleep_time = next_run - time.monotonic()
    time.sleep(sleep_time)
  • Related