Python Background Thread Timer

26 Views Asked by At
def run_timer(duration):
  import threading
  import time
  import sys
  
  class Timer:
    def __init__(self , duration):
      self.duration = duration
      self.remaining_time = duration
      self.timer_thread = threading.Thread(target=self.run_timer)
      self.timer_thread.daemon = True
      self.timer_thread.start()

    def run_timer(self):
      start_time = time.time()
      while self.remaining_time > 0:
        elapsed_time = time.time() - start_time
        self.remaining_time = max(0,self.duration - elapsed_time)
        self.display_time()
        time.sleep(1)
      print("Timer fin")

    def display_time(self):
      minutes , seconds = divmod(int(self.remaining_time) , 60)
      print(f"Time remaining: {minutes:02d}:{seconds:02d}" , end="\r")

    def stop_Timer(self):
      pass

  timer = Timer(duration)

  try:
    input()
    timer.stop_Timer()
  except KeyboardInterrupt:
    timer.stop_Timer()

Above is the code I have tried, it somewhat works but defo not as I want it to.. I don't know how to fix I just tried youtube google chatgpt nothing helped been working on this damn tiemr than my whole program itself.

Basically what i want is the user to be able to exit the timer while it still running in the background (counting down) and if the user for example in my case (timer is used for a game and i want to put a delay so user cant just do a thing over and over again) and if the user re tries to do that it ll show them how long they still have to wait (timer still counting down) until they can do it again or if it has finished they can just continue

0

There are 0 best solutions below