0

Since threading.Timer is a subclass of Thread, I would expect that the .join() in this script would cause the code to print "woof" once a second, continually:

import threading

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = threading.Timer(interval, target_action, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    timer.join()
    print("...exiting")

main()

Instead, it prints out "woof" once and then terminates (without any error message). What am I missing?

fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • Oops! On more careful reading of the docs, Timer doesn't loop -- it runs once. That explains what I'm seeing. Unless someone downvotes me, I'll leave the question so someone else can give the answer! :) – fearless_fool Jul 07 '17 at 23:51

1 Answers1

1

Here's what I really wanted (based loosely on https://stackoverflow.com/a/12435256/558639):

import threading

class IntervalTimer(threading.Thread):
    def __init__(self, target_action, interval, args=[]):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.target_action = target_action
        self.interval = interval
        self.args = args

    def start(self):
        while not self.event.wait(self.interval):
            self.target_action(*self.args)

def target_action(arg):
    print arg

def start_timer_proc(interval, arg):
    timer = IntervalTimer(target_action, interval, [arg])
    timer.start()
    return timer

def main():
    timer = start_timer_proc(1.0, "woof")
    print timer
    timer.join()
    print("...exiting")

main()

Note that I didn't need to change my target_action() or start_timer_proc() methods, except to instantiate an IntervalTimer rather than a Timer.

fearless_fool
  • 33,645
  • 23
  • 135
  • 217