0

I want to build a function that will stop another function after a set time.

For example:

def start():
    global bol_start
    bol_start = True
    timer()
    if bol_start is True:
       "do something until time is over"

def stop():
    global bol_start
    bol_start = False
    sys.exit(0)    

def timer():
    "code for actual timer" ?

I would like to let the user define the time x how long the tool should run start(). After the time is over it should call stop().

exec85
  • 447
  • 1
  • 5
  • 21
  • Does this answer your question? [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – Maurice Meyer Oct 07 '20 at 08:54
  • Hmmm anyway in this example too, you will have to say `global bol_start` in `stop()`, i recommend showing a better example though – Delrius Euphoria Oct 07 '20 at 08:56

1 Answers1

1

If you have a loop in the function, that runs continuously, the simplest mechanic would be to measure time every iteration:

import time

def run():
    start = time.time()
    stop_seconds = 10
    while time.time() - start < stop_seconds:
        # do something

If you don't have a loop or the function consists of time consuming operations, you would need to kill the function in the middle of execution like suggested here: Timeout on a function call

Wups
  • 2,489
  • 1
  • 6
  • 17