2014-01-27 34 views
1

在我目前正在实施中web.py Web服务器调用,我使用下面的方法来进行定期动作:多个线程在命令行

import threading  

def periodicAction(): 
    # do something 
    threading.Timer(time_interval, periodicAction).start() # when finished, wait and then start same function in a new thread 

periodicAction() # start the method 

虽然它工作正常(这意味着它做它应该做的),我仍然有问题,当我从命令行测试它时,控制台得不到响应(我仍然可以键入,但它没有影响,即使ctrl + c也不停止该程序)。这是正常的行为还是我做错了什么?

回答

1

后台线程仍在运行,所以如果主线程完成,它将等待 - 永远,在这种情况下。 (这是的一个副作用,如果它等待Ctrl-C不起作用。)如果你不想要这个,你可以调用setDaemon(True),这使得线程成为“守护进程” - 这意味着它将成为当主螺纹完成时强制关闭:

def periodicAction(): 
    print "do something" 
    t = threading.Timer(1.0, periodicAction) 
    t.setDaemon(True) 
    t.start()