5
\$\begingroup\$

I am currently using:

class RepeatedTimer(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.start()
            self.is_running = True

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

to run a section of code every 24 hours, however, this looks messy and I think it can be simplified.

I want to run a function every 24 hours. Is there a simpler and cleaner method?

\$\endgroup\$
3
  • \$\begingroup\$ is_running should be set Fals AFTER calling the function, not BEFORE. Right? \$\endgroup\$
    – Don
    Sep 8, 2014 at 13:42
  • 5
    \$\begingroup\$ Why are you trying to do this in Python, rather than using cron (or the Windows Task Scheduler) which are tools designed for just this purpose? \$\endgroup\$ Sep 12, 2014 at 18:30
  • \$\begingroup\$ What is the definition of class Timer? \$\endgroup\$
    – Tom Barron
    Nov 16, 2014 at 14:04

1 Answer 1

4
\$\begingroup\$

If the goal is to run a task at the same time each day, it is better to capture the value of the real-time clock, because using successive 24 hour intervals can give you a "time creep". Something along these lines would work fine (you'd probably put this in a separate thread):

import time

def time_of_day:
     return time.strftime("%H:%M:%S")

target_time = "18:00:00"

while True:
    while time_of_day() != target_time:
         time.sleep(.1)
    call_function()
    while time_of_day() == target_time:
         time.sleep(.1)
\$\endgroup\$
1
  • \$\begingroup\$ Oops. The original version used up cpu time. Corrected. \$\endgroup\$
    – RufusVS
    Dec 23, 2014 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.