1

I have thrown together a quick threading test:

import threading

def test():
    print "it don't work"
while True:
    threading.Timer(1, test).start()

It runs test, but it doesn't wait. What's wrong?

1
  • Runs fine (as expected) in Pyhton27. But you should put a time.sleep in that loop, to avoid killing the CPU. Commented Apr 27, 2017 at 17:54

1 Answer 1

2

In each loop iteration, you start a new thread. Therefore you will reach the limit of allowed thread and you will get an exception : can't start new thread.

while True:
    threading.Timer(1, test).start()

You can add global flag and wait until the function is executed - You should use time.sleep to avoid busy waiting.

a = False
def test():
    global a
    print("hallo")
    a = True
threading.Timer(10, test).start()
while not a:
    time.sleep(1)
print('done')
Sign up to request clarification or add additional context in comments.

2 Comments

I guess that I should have been more specific. I am trying to put this timer in a game event loop, so it needs to run serpratly from the rest of the program.
Well, After calling threading.Timer.start - you have two threads , the main thread and a thread which run the function in delay and exits.

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.