Advertisement
DeaD_EyE

TimeOutSwitch

May 29th, 2020
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. class TimeoutSwitch:
  2.     OFF = False
  3.     ON = True
  4.  
  5.     def __init__(self):
  6.         self.state = self.OFF
  7.         self.thread = None
  8.         self.cancel = False
  9.  
  10.     def callback(self, delay):
  11.         time.sleep(delay)
  12.         if self.cancel:
  13.             self.cancel = False
  14.         else:
  15.             self.state = self.OFF
  16.             print("Timeout -> Off")
  17.  
  18.     def timer(self, delay):
  19.         if self.cancel or self.thread is None or not self.thread.is_alive():
  20.             print("Started timeout")
  21.             self.thread = threading.Thread(target=self.callback, args=(delay,))
  22.             self.thread.start()
  23.  
  24.     def toggle(self):
  25.         if self.state == self.OFF:
  26.             self.state = self.ON
  27.             print("On")
  28.             self.timer(10)
  29.         else:
  30.             self.state = self.OFF
  31.             self.cancel = True
  32.             print("Off")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement