我有一个简单的程序来检测何时在目录中创建文件。它应该每分钟检查一次是否有新文件,如果没有新文件则重置计时器。
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 挂起,直到计时器完成为止。
最佳答案
这是我认为您想要的一个简单示例:
import os
import threading
def list_dir(my_dir, secs):
filenames = os.listdir(my_dir)
# print(filenames)
# Do your stuff here!!!
# Setting a new timer: call list_dir in secs seconds
threading.Timer(secs, list_dir, args=[my_dir, secs]).start()
def start_timer():
print('timer started!')
seconds = 60 # 60 seconds
directory = "/my/beloved/dir" # insert here the directory
threading.Timer(seconds, list_dir, args=[directory, seconds]).start()
start_timer()
请注意,Timer
仅调用其回调一次(在您指定为第一个参数的秒数之后),这就是我们在内部创建并启动另一个 Timer
的原因list_dir
。
关于python - 计时器未重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906221/