繁体   English   中英

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

[英]How can I make this timer run forever?

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()

一个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

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

只需重启(或重新创建)函数中的计时器:

#!/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()

来自线程导入计时器取决于你想要运行哪一部分,如果它正在创建一个新线程让我们说每隔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()

如果你想要永远运行你好的世界,你可以做到以下几点:

from threading import Timer

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

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

在python中搜索循环以获取有关此内容的更多信息

这是我的问题代码:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM