14

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...

2
  • Are there any other statements in your code? Why are you making the thread a daemon thread? If you have no other statements, python will exit if only daemon threads are left, and your thread will never have time to execute. Commented Mar 2, 2018 at 17:58
  • @BrendanAbel There are many threads :) Thank u! Commented Mar 2, 2018 at 23:58

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, the daemon argument will not be put in kwargs, because kwargs here is a single keyword argument, and not a double-star catcher. What happens when passing daemon=True is a TypeError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.