【发布时间】:2017-01-28 04:08:09
【问题描述】:
我有一个简单的程序来检测何时在目录中创建文件。它应该每分钟检查一次是否有新文件,如果没有新文件则重置计时器。
import os
import threading
import time
import sys
def detector():
filenames = os.listdir('/home/username/Documents/')
if filenames:
for i in filenames:
#do things
print('I started a thread!')
sys.stdout.flush()
threading.Thread(target=start_timer).start()
def start_timer():
print('I started a threaded timer at', t.ctime())
sys.stdout.flush()
threading.Timer(60, detector)
#UI stuff here
在目录中没有文件的情况下运行时,脚本只会打印出来:
I started a thread!
I started a timer at [insert time here]
但只有一次。这让我觉得我的线程有问题(我以前从未使用过线程)。我不知道它是否必须是线程的,但程序不能等待一个正常的计时器,因为一个计时器让 UI 挂起,直到计时器完成。
【问题讨论】:
-
你想通过将
detector末尾创建的线程的目标设置为start_timer,然后将Timer的回调设置为detector来达到什么目的?顺便说一句,Timer是Thread的子类,所以要启动它,理论上你必须调用start... -
哦......是的......开始......我希望启动一个计时器来检查是否在没有 UI 挂起的情况下创建了文件。
-
多线程不是一项简单的编程任务。您必须先了解基础知识...
标签: python multithreading python-3.x timer