patternpythonMinor
Better method of a timer in Python
Viewed 0 times
timerpythonbettermethod
Problem
I am currently using:
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?
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 = Falseto 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?
Solution
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):
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)Code Snippets
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)Context
StackExchange Code Review Q#62273, answer score: 4
Revisions (0)
No revisions yet.