1

Suppose I want to restart an event loop by an interval time, such as below:

from time import sleep

def event_loop():
    print('Restart')
    while True: # Note :: This is an indefinite loop
        # Process some stuff.
        print("I'm a process")
        sleep(1)

magic_tool(interval_time=5, func=event_loop)

Expected result:

Restart
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
Restart
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
Restart
I'm a process
.
.
.

I read about twisted, threading.Timeand apscheduler.scheduler but I couldn't do that.

I think I can do it by async.timeout.timeout() but I'm using Python2.7

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
  • Have a look at https://stackoverflow.com/questions/34562473/most-pythonic-way-to-kill-a-thread-after-some-period-of-time –  Dec 02 '18 at 09:43

2 Answers2

1

Try this:

import threading 

def event_loop():
    print("do_something") 

some_flag=True
while some_flag:
    timer = threading.Timer(2.0, event_loop) 
    timer.start() 
Yakov Dan
  • 2,157
  • 15
  • 29
1

I found a solution with creating a stoppable thread:

import threading
import time

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        print('Restart')
        while True and not self.event.is_set():
            print("I'm a process")
            self.event.wait(1)

    def stop(self):
        self.event.set()

try:
    while True:
        tmr = TimerClass()
        tmr.daemon = True
        tmr.start()
        time.sleep(5)
        tmr.stop()

except KeyboardInterrupt:
    pass

Expected result:

Restart
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
Restart
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
I'm a process
Restart
I'm a process
I'm a process
.
.
.
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150