Search code examples
pythonwhile-loopinfinite-loopstock

In an infinite loop, is there any module that can temporary suspend a function of one of the variables for a specific time (eg. 10min)?


I have an infinite loop running code that gathers live data from an outside source.

while True:

    x = Livedata() # this should stop for 10 mins when x < 30, then restart.
    y = Livedata()
    z = Livedata()

I want the code to suspend gathering data for N minutes for the x variable when a certain condition is met, e.g. x < 30. The code should not stop gathering data for y and z when x is suspended. After N minutes, gather data for x again until the condition is met again.


Solution

  • I think threads would be the best option, but if you want a thread-free way, you could use something like time.time() to keep track of every start moment for each thing you want to do.

    This runs the code for x always if x > 30, otherwise it skips x = liveData() for 10 minutes. After 10 minutes it restarts. y and z just do what they already did.

    import time
    
    def minutesPast(end_time, start_time):
        return ( end_time - start_time ) / 60
    
    TIME_INTERVAL = 10 # minutes
    
    x_start = time.time()
    
    # your loop
    while True:
    
        time_now = time.time()
    
        # code for 'x'
        if ( x > 30 ) or (minutesPast(time_now, x_start) > TIME_INTERVAL) :
            x_start = time.time()
            x = liveData()
    
        y = liveData()
        z = liveData()