Set a boolean for a certain laps of time while pro

2019-06-05 03:44发布

问题:

I was wondering if there is an easy and simple way to set a boolean to True for a certain laps of time. After, it set back to False. All those actions made while the program continue running.

Maybe I could do this with theads and timer?

E.g.

main()
decrease = Decrease()
decrease.run()

class Decrease()
  def __init__(self)
    self.value = 4
    self.isRunning = false

  def run(self)
    while True:
      self.checkIfValueIsDecreasing()
      time.sleep(2)


  def checkIfValueIsDecreasing(self)
    if self.value < 1
      self.isDecreasing = True
      time.sleep(60)
      self.isDecreasing = False

This is only a quick exemple. But in this case, I check is the value is decreasing every 2 second. If yes, then I set the isDecreasing value to True for 1 minutes.

The problem is that the program doesn't continue running. I would like the run method to continue running every 2 sec...

Someone have any clue on that?

回答1:

I suppose you could use threads to run the Decrease.run method in the background.

d = Decrease()
t = threading.Thread(target=d.run)
t.daemon = True
t.start()

Of course you can implement threads directly in the Decrease.run method, example:

class Decrease:
    def __init__(self):
        self.value = 4
        self.isDecreasing = False

    def run(self): 
        def run_thread():
            while True:
                self.checkIfValueIsDecreasing()
                time.sleep(2)
        t = threading.Thread(target=run_thread)
        t.daemon = True
        t.start()


回答2:

There is a helper function in the threading module that does exactly what you want, namely the Timer. This will start a timer in a separate thread and when the Timer object times out, a pre-defined function is called. An example based on your use case, modified to work and show the behavior, would be:

import time
from threading import Timer

class Decrease():
    def __init__(self):
        self.value = 4
        self.isDecreasing = False

    def run(self):
        while True:
            self.checkIfValueIsDecreasing()
            time.sleep(2)
            if (self.isDecreasing):
                self.value += 1
            else:
                self.value -= 1
            print(self.value)

    def checkIfValueIsDecreasing(self):
        if self.value < 1:
            self.isDecreasing = True
            timer = Timer(60, self.timeOut)
            timer.start()

    def timeOut(self):
        self.isDecreasing = False

decrease = Decrease()
decrease.run()