Search code examples
pythontimed-events

python timed execution of code


I want to execute a piece of my code in exactly the same time every time I execute it, somewhat like playing a media file... (the same piece of code is executed in exactly the same amount of time every time)

Is this possible in python?


Solution

  • This should do the trick:

    def run_with_delay(funcs, interval):
        for f in funcs[:-1]:
            before = time()
            f()
            # compensate the interval with the execution time.
            # NB: careful for functions that have a greater
            #     execution time than interval
            after = time()
            if after - before < interval:
                sleep(interval - (after - before))
        # last function is taken separately because we don't need
        # an extra useless sleep
        funcs[-1]()