-3

I have a function which keeps capturing the data from live stream. I want to run this code for 30 minutes.

2 Answers2

5

You can easily achieve this using the datetime module with a while loop:

from datetime import datetime, timedelta

start_time = datetime.now()

while datetime.now() - start_time <= timedelta(minutes=30):
    ... your code ...

By doing it like this, your code will get repeated until the difference between the current time and the start time is less than or equal to 30 minutes, meaning it will stop once it will reach 30 minutes.

Daniel
  • 487
  • 4
  • 11
1

A possible way could be to run the function in a separate process and make it terminates when the parent tells it to (sets the quit event):

import time
import multiprocessing as mp

def your_function(args, quit):
    while not quit.is_set():
        ... # your code
    return

if __name__ == '__main__':
    quit = mp.Event()
    p = mp.Process(target=your_function, args=(args, quit))
    p.start()
    time.sleep(1800) # in sec, half an hour
    quit.set()

The advantage of using mltiprocessing is that you can do other stuff while the other process listens to the call.

Neb
  • 2,270
  • 1
  • 12
  • 22