Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling thread.timer() more than once

The code:

from threading import Timer
import time

def hello():
    print "hello"

a=Timer(3,hello,())
a.start()
time.sleep(4)
a.start()

After running this script I get error: RuntimeError: threads can only be started once so how do I deal with this error. I want to start the timer more than once.

like image 409
Nil Avatar asked Mar 20 '23 05:03

Nil


1 Answers

threading.Timer inherits threading.Thread. Thread object is not reusable. You can create Timer instance for each call.

from threading import Timer
import time

class RepeatableTimer(object):
    def __init__(self, interval, function, args=[], kwargs={}):
        self._interval = interval
        self._function = function
        self._args = args
        self._kwargs = kwargs
    def start(self):
        t = Timer(self._interval, self._function, *self._args, **self._kwargs)
        t.start()

def hello():
    print "hello"

a=RepeatableTimer(3,hello,())
a.start()
time.sleep(4)
a.start()
like image 125
comuri Avatar answered Apr 01 '23 21:04

comuri