timer.py
Brut
import threading
import time
class SleeperThread(threading.Thread):
def __init__(self, sleep_interval):
super().__init__()
self.sleep_interval = sleep_interval
self.stop_event = threading.Event()
def run(self):
while not self.stop_event.is_set():
# Do task here
time.sleep(self.sleep_interval)
def stop(self):
self.stop_event.set()
Usage:
python
thread = SleeperThread(30) # sleep 30 seconds
thread.start()
# To stop thread
thread.stop()
| 1 | import threading |
| 2 | import time |
| 3 | |
| 4 | class SleeperThread(threading.Thread): |
| 5 | def __init__(self, sleep_interval): |
| 6 | super().__init__() |
| 7 | self.sleep_interval = sleep_interval |
| 8 | self.stop_event = threading.Event() |
| 9 | |
| 10 | def run(self): |
| 11 | while not self.stop_event.is_set(): |
| 12 | # Do task here |
| 13 | time.sleep(self.sleep_interval) |
| 14 | |
| 15 | def stop(self): |
| 16 | self.stop_event.set() |
| 17 | |
| 18 | |
| 19 | Usage: |
| 20 | |
| 21 | python |
| 22 | |
| 23 | thread = SleeperThread(30) # sleep 30 seconds |
| 24 | thread.start() |
| 25 | |
| 26 | # To stop thread |
| 27 | thread.stop() |