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

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

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

    def stop(self):
        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?

  • \$\begingroup\$ is_running should be set Fals AFTER calling the function, not BEFORE. Right? \$\endgroup\$
    – Don
    Commented 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\$ Commented Sep 12, 2014 at 18:30
  • \$\begingroup\$ What is the definition of class Timer? \$\endgroup\$
    – Tom Barron
    Commented Nov 16, 2014 at 14:04

1 Answer 1


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:
    while time_of_day() == target_time:
  • \$\begingroup\$ Oops. The original version used up cpu time. Corrected. \$\endgroup\$
    – RufusVS
    Commented Dec 23, 2014 at 20:31

Your Answer

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

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