简体   繁体   English

(python) 每 x 秒执行一次函数

[英](python) execute function every x seconds

this is my source code that executes function every 1 seconds这是我每 1 秒执行一次函数的源代码

buy, it only executes one times.购买,它只执行一次。

In short, I want to get the # of line from the named pipe output every seconds总之,我希望得到#从命名管道输出线的每一秒

Is there any suggestion for this problem?对这个问题有什么建议吗?

thank you for your help in advance提前谢谢你的帮助

class Monitor:
    def __init__(self, namedpipe, name):
        self.namedpipe = namedpipe
        self.name = name
        self.count = 0
    def run(self):
        print self.name+" start run"
        while True:
            line = self.namedpipe.readline()
            self.count = self.count+1
    def getCost(self):
        print "Hi"


while True:
    line = monitor.readline()
    line = line.strip()
    if not line: 
        ans =raw_input('stop?')
        if ans=='y': break
    monitorList = open(line, 'r')
    m = Monitor(monitorList, line)
    thread.start_new_thread(m.run, ())
    time.sleep(1)
    threading.Timer(0.1, m.getCost).start()

With Threading.Timer, you have to restart the timer each time it has expired - so during the execution of the function called when the timer expires - m.getCost in your code - the timer has to be started again.使用 Threading.Timer,您必须在每次计时器到期时重新启动计时器 - 因此在计时器到期时调用的函数的执行期间 - 代码中的 m.getCost - 计时器必须再次启动。 You might want to define a wrapper function to do this work, to avoid polluting m.getCost() with timer stuff.您可能想要定义一个包装函数来完成这项工作,以避免使用计时器的东西污染 m.getCost()。

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

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