如何使这个定时器永久运行?

4
from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start()

这段代码只会启动一次计时器。

我该如何让计时器一直运行下去?

谢谢!

更新

以下代码是正确的:

import time,sys

def hello():
    while True:
        print "Hello, Word!"
        sys.stdout.flush()
        time.sleep(2.0)
hello()

并且还有这个:

from threading import Timer

def hello():
    print "hello, world"
    sys.stdout.flush()
    t = Timer(2.0, hello)
    t.start()

t = Timer(2.0, hello)
t.start()
5个回答

9
一个 threading.Timer 执行一个函数,该函数只执行一次。如果你愿意,该函数可以“永久运行”,例如:
import time

def hello():
    while True:
        print "Hello, Word!"
        time.sleep(30.0)

使用多个 Timer 实例会消耗大量资源,但并不能带来真正的附加价值。如果您想对每30秒重复执行的功能不进行干扰,一个简单的方法是:

import time

def makerepeater(delay, fun, *a, **k):
    def wrapper(*a, **k):
        while True:
            fun(*a, **k)
            time.sleep(delay)
    return wrapper

然后安排 makerepeater(30, hello) 而不是 hello

对于更复杂的操作,建议使用标准库模块sched


但是我看不到打印任何东西。 - zjm1126
嗨 Alex,你知道如何在线程中实现这个吗?谢谢。 - zjm1126
“print” 从线程中打印(假设您所说的是“therad”)可能不是一个好主意——“logging” 模块保证是线程安全的,而“print”则不是。无论如何,如果您使用“Timer”调度“makerepeater”的结果,它当然会(尝试)在自己的线程中运行。 - Alex Martelli

9

只需在函数内重新启动(或重新创建)计时器:

#!/usr/bin/python
from threading import Timer

def hello():
    print "hello, world"
    t = Timer(2.0, hello)
    t.start()

t = Timer(2.0, hello)
t.start()

我知道,是吧?似乎每个回答都被莫名其妙地踩了。 - zneak
作者或其他人似乎在恶意攻击 :/ - user202459
这个对我不起作用:raise RuntimeError("thread already started") - daniel
1
@zoodbergi,不确定你做错了什么,这在2.7.3和3.2.3中都可以正常工作(一旦给print加上括号)。没有引发任何异常。 - paxdiablo
似乎不可能重新启动现有的 Timer,但是将您的标识符 t 重新绑定到一个新的 Timer,然后启动它是可能的,这就是此示例显示的内容。我假设 @zoidbergi 您没有创建新的计时器,因此出现了错误。(根据文档,TimerThread 的子类。) - boycy

2
你可以通过子类化threading.Timer类并重写run方法来创建一个重复定时器,以使用循环。
from threading import Timer

class RepeatingTimer(Timer):
    
    def run(self):
        """Start the timer (overrides Thread.run)."""
        while True:
            # Wait for the set flag or timeout.
            self.finished.wait(timeout=self.interval)
            if not self.finished.is_set():
                self.function(*self.args, **self.kwargs)
            else:
                # Do not need to set the finished event flag since this loop
                # will only end if the flag is set.
                break

请参阅计时器类实现以及事件文档,获取更多信息。


1

从线程中导入计时器 这取决于您想永久运行哪个部分,如果它是每10秒创建一个新线程,您可以执行以下操作 从线程中导入计时器

import time
def hello():
    print "hello, world"

while True: #Runs the code forever over and over again, called a loop
    time.sleep(10)#Make it sleep 10 seconds, as to not create too many threads
    t = Timer(30.0, hello)
    t.start()

如果你想永远运行“Hello World”,可以执行以下操作:
from threading import Timer

def hello():
    while True: # Runs this part forever
        print "hello, world"

t = Timer(30.0, hello)
t.start()

搜索Python中的循环以获取更多信息


0
这是我针对这个问题的代码:
import time
from  threading import Timer

class pTimer():
    def __init__(self,interval,handlerFunction,*arguments):
        self.interval=interval
        self.handlerFunction=handlerFunction
        self.arguments=arguments
        self.running=False
        self.timer=Timer(self.interval,self.run,arguments)

    def start(self):
        self.running=True
        self.timer.start()
        pass

    def stop(self):
        self.running=False
        pass

    def run(self,*arguments):
        while self.running:
           self.handlerFunction(arguments)
           time.sleep(self.interval)

另一个脚本页面:

def doIt(arguments):
    #what do you do
    for argument in arguments:
        print(argument)

mypTimer=pTimer(2,doIt,"argu 1","argu 2",5)

mypTimer.start()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接