Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在不运行函数的情况下创建Python计时器_Python_Timer - Fatal编程技术网

在不运行函数的情况下创建Python计时器

在不运行函数的情况下创建Python计时器,python,timer,Python,Timer,在Python中,是否可以创建/设置带有线程的计时器,但在调用thread.start()之前不运行该函数?我设置了一个永久计时器,如下所示: class perpetualTimer(): enabled = False Interval = 0 def __init__(self,t,hFunction): print("init") self.t=t self.Interval = t self.hFunction = hFunc

在Python中,是否可以创建/设置带有线程的计时器,但在调用thread.start()之前不运行该函数?我设置了一个永久计时器,如下所示:

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")
然后创建它:

tmr = perpetualTimer(5,foo())
然后运行这个程序,我得到一个“foo”的打印输出,后跟“init”。。。不是我想要的。。。。我只希望它在写入时打印“init”

tmr = perpetualTimer(5,foo())
你说“在5号上调用永久化器,然后调用foo的结果”。这就是为什么“foo”在“init”之前打印

看看你的代码,我觉得你在寻找

tmr = perpetualTimer(5,foo)

只传递对函数的引用

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

 tmr = perpetualTimer(5,foo)

是的,我在发布问题后不久就意识到了这一点。菜鸟错误。。。