Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no Timer class in Python's multiprocessing module?

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?

like image 934
Manas Avatar asked Aug 13 '14 23:08

Manas


1 Answers

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?

like image 169
dano Avatar answered Sep 22 '22 12:09

dano