0

My threading is set up exactly like the top answer from here. Except that my function is more complex than a print.

import threading

def printit():
  threading.Timer(10.0, printit).start()
  print "Hello, World!"

printit()

The function takes about 6 seconds to run. On rare occasions, it takes 12-13 seconds to run. Without incurring opportunity costs by extending the wait time, how do I make this timer wait until the function runs?

  • why is it in a thread at all if you want to wait until the code finishes before continuing? why not just have it in a loop? – Joran Beasley May 26 '20 at 06:32
  • Hi, thanks for your reply. I see what you mean but my function is a bit complicated but one aspect is the data it pulls relies on timing. I find threading to suits my needs here. – MischievousBear May 26 '20 at 06:38

1 Answers1

1

threading.Timer(10.0, printit).start()

Is just a thread

you can capture it

def printit():
    thread = threading.Timer(10.0, printit)
    thread.start()
    # ... some stuff or something
    thread.join() # wait for thread to finish ?

is maybe one way you could ... but why not just skip the timer and do it at the end? or really why not just put it in a loop?

def printit():

    # ... some stuff or something
    threading.Thread(target=printit).start() # now you dont need to worry about it

but i really dont understand why you are not just using a loop ... this seems like it adds complexity without actually achieving anything useful for you

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thank you for your answer. I'll be right back. Testing the code. – MischievousBear May 26 '20 at 07:00
  • Thanks Joran. I can confirm that both codes work. I actually went with your second suggestion as the first raised more issues. With my code, I just added a few time.sleep() to make it work with putting a timer at the end. – MischievousBear May 26 '20 at 08:53