threading.Timer join()立即退出?

时间:2017-07-07 23:49:18

标签: multithreading python-2.7

由于threading.TimerThread的子类,我希望此脚本中的.join()会导致代码每秒打印一次“woof”,不断:

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()

相反,它打印出“woof”一次然后终止(没有任何错误消息)。我错过了什么?

1 个答案:

答案 0 :(得分:1)

这就是我真正想要的东西(基于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()

请注意,除了实例化target_action()而不是start_timer_proc()之外,我无需更改IntervalTimerTimer方法。