parallel.py 948 Bytes
Newer Older
Simon Sebastian Humpohl's avatar
Simon Sebastian Humpohl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import threading
import time


class ThreadedPeriodicCallback:
    """Periodically call the given function. Dont forget to call start. You can change the period while it runs.
    Be aware that your callback needs to be thread safe. This means you need to make sure that the state there is always
    consistent.

    Example:
        >>> pcb = ThreadedPeriodicCallback(1., lambda: print('my function'))
        >>> pcb.start()

        >>> pcb.stop()
    """
    def __init__(self, period: float, callback: callable):
        self._stop = False
        self.period = period
        self.callback = callback
        self.thread = threading.Thread(target=self._run)

    def _run(self):
        while not self._stop:
            self.callback()
            time.sleep(self.period)

    def stop(self):
        self._stop = True
        self.thread.join()

    def start(self):
        self.thread.start()

    def __del__(self):
        self.stop()