Python线程,启动线程产生2个线程

时间:2015-08-06 13:32:15

标签: python multithreading python-2.7 flask

我正在创建一个Flask服务器,并希望在后台运行一个进程,该进程将定期调用一个函数并在那里执行代码。为了测试这是否可行,我做了一个简单的函数,只打印出datetime()然后再等待10秒再循环。为了让服务器像往常一样运行,我还尝试将此函数放在它自己的线程中,以允许它拼命运行,不会影响服务器处理传入的请求。我的代码如下:

def periodic_calls():
while True:
    print datetime.datetime.now()
    print 'Thread Count: ' + str(threading.active_count())
    time.sleep(10)


if __name__ == '__main__':
    timerThread = threading.Thread(target=periodic_calls)
    timerThread.start()
    app.debug=True
    app.run()

此代码的大部分都来自Executing periodic actions in Python

问题是函数periodic_calls()内的代码似乎每10秒调用两次而不是一次。上述代码的输出:

2015-08-06 14:27:51.825000
Thread Count: 2
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
2015-08-06 14:27:52.265000
Thread Count: 2
2015-08-06 14:28:01.828000
Thread Count: 2
2015-08-06 14:28:02.268000
Thread Count: 3
2015-08-06 14:28:11.829000
Thread Count: 2
2015-08-06 14:28:12.268000
Thread Count: 3
2015-08-06 14:28:21.830000
Thread Count: 2
2015-08-06 14:28:22.269000
Thread Count: 3

是什么原因导致第三个线程启动并且函数被调用两次而不是一次?我该如何纠正这个?

0 个答案:

没有答案