0

I have a program which has two threads: the first one, constantly receives data, the second one, once some data has been received, it processes it every 60 seconds.

Within this second thread, there's also a sort of 'debug' printing happening, which I need to slow down to 3 minutes in between prints.

This is roughly the pseudocode of what's happening:

def data_stream():
    data.append(new_data)

def process_data():
    data.update()
    print(data)
    time.sleep(60)

def main():
    # I handle threading here

As you can see I want to add an if statement or something before the print to make sure that the printing is done once every 3 minutes. How can I do this?

G. Ramistella
  • 1,327
  • 1
  • 9
  • 19
  • if `process_data` contains a loop, just keep track of (60 second) iterations and only print every third iteration. – wwii Jun 25 '19 at 18:31
  • What if I want to be more flexible? Like maybe I want change the rate of both (not necessarily 60 seconds sleep and 3 minute print) – G. Ramistella Jun 25 '19 at 18:40
  • Related: [Executing periodic actions in Python (duplicate)](https://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python) ... – wwii Jun 25 '19 at 18:49
  • and ...[Python threading.timer - repeat function every 'n' seconds](https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds) – wwii Jun 25 '19 at 18:54

1 Answers1

0

Have a counter initially set to 0. Each time process_data wakes up from sleeping (every 60 seconds), it increments the counter by 1. When the counter reaches 3, it has been 180 seconds or 3 minutes since the last print. So, it issues the print operation and resets the counter back to 0.

OR

If the sleep duration is variable:

Instead of a counter, initialize a variable next_print_time with a call to time.time() + 180. This will be when you want to do the next print operation. Then every time you wake up, call time.time() and compare the result with next_print_time to determine whether you should print or not and compute and save in next_print_time a new value if you did just print. It gets a bit tricky when N, the number of seconds between calls to your function does not evenly divide 180. If N is much smaller than 180, then it is probably adequate just to compare the current time of day with next_print_time and if it is greater, then print. But let's say N was 80. After 2 calls you would still have 20 seconds to go. But if you wait for one more call, you would be 60 seconds late. In that case I would do the print now. But in computing the next expiration time next_print_time, I would ALWAYS add 180 to the current value of next_print_time so that you AVERAGE one print every 180 seconds.

Booboo
  • 38,656
  • 3
  • 37
  • 60