Home > OS >  how do I stop this while loop after a specific time?
how do I stop this while loop after a specific time?

Time:05-22

I'm currently making a lightning code, but I have some problems with the while loop. I want to stop the While loop after a specific time that I set. here's the code.

class Light:
    def __init__(self):
        self.work_flag = False

    def start(self):
        self.work_flag = True

    def stop(self):
        self.work_flag = False


    def mode_1(self):
        print("turn on red green blue light")
        sleep(0.5)
        while self.work_flag:
            print("turn on red light")
            sleep(0.3)
            print("turn on green light")
            sleep(0.3)
            print("turn on blue light")
            sleep(0.3)
            print("turn on red green light")
            sleep(0.3)
            print("turn on red blue light")
            sleep(0.3)
            print("turn on green blue light")
            sleep(0.3)

light = Light()

def light_start():
    light.start()
    light.mode_1()

def light_stop():
    light.stop()

light_start()
sleep(5)
light_stop()

CodePudding user response:

Maybe you should add elapsed_time method. It will wait until all the work is done in 'while' but I think it's not bad at all.

import time

class Light:
    def __init__(self):
        self.work_flag = False

    def start(self):
        self.startTime = time.time() # start time
        self.work_flag = True

    def stop(self):
        self.work_flag = False


    def mode_1(self):
        self.endTime = time.time() # end time
        elapsedTime = self.endTime - self.startTime # elapsed time
        print("turn on red green blue light")
        time.sleep(0.5)
        
        #if elapsedTime > 5: the work is done.
        while self.work_flag and elapsedTime < 5: # 5 seconds
            self.endTime = time.time() # end time
            elapsedTime = self.endTime - self.startTime # elapsed time
            print(elapsedTime)
            print("turn on red light")
            time.sleep(0.3)
            print("turn on green light")
            time.sleep(0.3)
            print("turn on blue light")
            time.sleep(0.3)
            print("turn on red green light")
            time.sleep(0.3)
            print("turn on red blue light")
            time.sleep(0.3)
            print("turn on green blue light")
            time.sleep(0.3)

light = Light()

def light_start():
    light.start()
    light.mode_1()

def light_stop():
    light.stop()

start = time.time()
light_start()
time.sleep(5)
light_stop()
  • Related