【问题标题】:Timer not resetting定时器不复位
【发布时间】: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来达到什么目的?顺便说一句,TimerThread 的子类,所以要启动它,理论上你必须调用start...
  • 哦......是的......开始......我希望启动一个计时器来检查是否在没有 UI 挂起的情况下创建了文件。
  • 多线程不是一项简单的编程任务。您必须先了解基础知识...

标签: python multithreading python-3.x timer


【解决方案1】:

这是我认为您想要的一个简单示例:

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 仅调用其回调一次(在您指定为第一个参数的秒数之后),这就是我们在 list_dir 内创建并启动另一个 Timer 的原因。

【讨论】:

  • 我会在早上测试它。但重要的是:计时器是否会在程序完成之前暂停程序(例如:理论上的 UI 按钮是否仍然有效?) 编辑:一旦我早上检查答案,我会接受答案。
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
相关资源
最近更新 更多