O
O
Old_TyT2021-07-29 08:38:56
Python
Old_TyT, 2021-07-29 08:38:56

How to run a function for a specific time in python?

How to run a function, for example, for X minutes, so that after X minutes the function completes its work without terminating the main program?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur Samurai, 2021-07-29
@Old_TyT

from threading import Timer
import time


class RepeatTimer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)


def your_func(msg="do something"):
    print(msg)


timer = RepeatTimer(1, your_func)
timer.start()
time.sleep(10)
timer.cancel()

A simple example of using a timer in threads. This will run your_func() for 10 seconds.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question