Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading timer initial daemon

This code is not working......

self._thread = threading.Timer(interval=2, 
                               function=self._sendRequestState, 
                               args=(self._lockState,), 
                               daemon=True).start()

So I should write down like this..

self._thread = threading.Timer(interval=2, 
                               function=self._sendRequestState, 
                               args=(self._lockState,))
self._thread.daemon = True
self._thread.start()

But the Timer class has Thread.__init__, Thread.__init__ has "daemon" for input parameter. I don't have any idea why it doesn't work...

like image 972
Hazel Avatar asked Feb 05 '23 01:02

Hazel


1 Answers

You can find the source code of that threading.Thread() constructor here (of cpython, the most common python implementation):

def __init__(self, interval, function, args=None, kwargs=None):
    Thread.__init__(self)
    self.interval = interval
    self.function = function
    self.args = args if args is not None else []
    self.kwargs = kwargs if kwargs is not None else {}
    self.finished = Event()

If you pass daemon=True into it, that will be put in kwargs, but as you can see in the code, nothing happens with it. So yes, you're correct, you'll have to set the daemon attribute after creating it (and before calling start(). There seems to be no option to set it directly when constructing the Timer.

like image 97
Dennis Soemers Avatar answered Feb 06 '23 14:02

Dennis Soemers