如何让这个计时器永远运行?

zjm*_*126 4 python multithreading timer

from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start()
Run Code Online (Sandbox Code Playgroud)

此代码仅触发计时器一次.

如何让计时器永远运行?

谢谢,

更新

这是正确的 :

import time,sys

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

还有这个:

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()
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 9

一个threading.Timer执行的函数一次.如果您愿意,该功能可以"永远运行",例如:

import time

def hello():
    while True:
        print "Hello, Word!"
        time.sleep(30.0)
Run Code Online (Sandbox Code Playgroud)

使用多个Timer实例会消耗大量资源而没有真正的附加值.如果你想要每30秒重复一次的功能,那么一个简单的方法就是:

import time

def makerepeater(delay, fun, *a, **k):
    def wrapper(*a, **k):
        while True:
            fun(*a, **k)
            time.sleep(delay)
    return wrapper
Run Code Online (Sandbox Code Playgroud)

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

对于更复杂的操作,我建议标准库模块附表.


pax*_*blo 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()
Run Code Online (Sandbox Code Playgroud)