Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
    
is_running should be set Fals AFTER calling the function, not BEFORE. Right? –  Don Sep 8 '14 at 13:42
5  
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? –  Gareth Rees Sep 12 '14 at 18:30
    
What is the definition of class Timer? –  Tom Barron Nov 16 '14 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:
         time.sleep(.1)
    call_function()
    while time_of_day() == target_time:
         time.sleep(.1)
share|improve this answer
    
Oops. The original version used up cpu time. Corrected. –  RufusVS Dec 23 '14 at 20:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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