How to run threads at a certain interval in python?

Viewed 30

I need to create a program that will run threads at a certain interval. The interval and name are specified in the class constructor.

class IntervalThread(threading.Thread):
    def __init__(self, name=None):
        super().__init__(group, target, name, args, kwargs, daemon=daemon)
        self.interval = interval

I start two threads and they work random time. When first thread is over i need start new thread through interval time.

The problem is that when waiting for a thread with a longer interval, a thread with a short interval waits for the end of a long interval.

if __name__ == "__main__":
    event = threading.Event()
    IntervalThread(name="first", interval=1, target=work_imitation).start()
    IntervalThread(name="third", interval=5, target=work_imitation).start()
    threads = [threading.enumerate()][0]
    threads.pop(0)
    while True:
        event.wait()
        for i in threads:
            if not i.is_alive():
                threads.remove(i)
                thread = IntervalThread(
                    name=i.name,
                    interval=i.interval,
                    target=work_imitation,
                )
                thread.start()
                threads.append(thread)
                event.clear()
0 Answers
Related