简体   繁体   English

在不运行函数的情况下创建Python Timer

[英]Creating a Python Timer without running the function

Is it possible in Python to create/setup a timer with threading, but not run the function until thread.start() is called? 在Python中是否可以使用线程创建/设置计时器,但是直到调用thread.start()才能运行该函数? I've setup a perpetual timer like so: 我已经设置了一个永久计时器,如下所示:

class perpetualTimer():
  enabled = False
  Interval = 0
  def __init__(self,t,hFunction):
      print("init")
      self.t=t
      self.Interval = t
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

  def handle_function(self):
      print("handle")
      print(self.hFunction.__name__)
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      self.thread.start()

  def start(self):
      print("start")
      self.thread = Timer(self.Interval,self.handle_function)
      self.thread.start()

  def stop(self):
      print("stop")
      self.thread.cancel()
def foo():
  print("foo")

And then create it: 然后创建它:

tmr = perpetualTimer(5,foo())

By then running the program, I get a print out of "foo", followed by "init"... Not what I want.... I just want it to print "init" 然后运行程序,我得到“ foo”的打印结果,然后是“ init”。不是我想要的...。我只希望它打印“ init”。

When writing 写作时

tmr = perpetualTimer(5,foo())

You say "call perpetualTimer on 5 and the result of a call to foo". 您说“在5上调用perpetualTimer以及对foo的调用结果”。 That is why "foo" is printed before "init". 这就是为什么在“ init”之前打印“ foo”的原因。

Looking at your code it seems to me like you are rather looking for 查看您的代码在我看来,您似乎正在寻找

tmr = perpetualTimer(5,foo)

passing only a reference to the function! 仅传递对该函数的引用!

发现了问题:对perpetualTimer(5,foo())的调用实际上应该是

 tmr = perpetualTimer(5,foo)

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

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