So the threading
module has a Timer
class inhereted from Thread
class to repeatedly execute some tasks.
I was wondering why doesn't the multiprocessing module have something like an analogous TimedProcess
class for e.g., which is inhereted from Process
to repeatedly execute some tasks?
It is possible to write such a timed process and I have written one but still curious. Or am I missing something?
It's pretty straightforward to implement yourself:
from multiprocessing import Process, Event
class Timer(Process):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
I'm not sure why there isn't one included in the stdlib. Perhaps because its less likely to be useful?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With