python - 计时器未重置

标签 python multithreading python-3.x timer

我有一个简单的程序来检测何时在目录中创建文件。它应该每分钟检查一次是否有新文件,如果没有新文件则重置计时器。

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/

相关文章:

python - -1 返回 python 列表中倒数第二个项目

python - 使用分隔符将文件中的多行存储到变量

c++ - C++中c_str()的线程安全

python-3.x - 将图像保存为字节并上传到 boto3 返回内容 MD5 不匹配

python-3.x - 在 numpy 中获取索引

Java 线程与 Pthread

python - 检查范围内的东西的运行时间

python - 如何在 Gremlin-Python 中使用 "neq"?

python - 如何使用 TAL 访问数组

Java scheduleAtFixedRate 在 2 次后停止工作