Last active 1698929318

timer.py Raw
1import threading
2import time
3
4class 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
19Usage:
20
21python
22
23thread = SleeperThread(30) # sleep 30 seconds
24thread.start()
25
26# To stop thread
27thread.stop()