简体   繁体   English

threading.Timer()

[英]threading.Timer()

i have to write a program in network course that is something like selective repeat but a need a timer.我必须在网络课程中编写一个类似于选择性重复但需要计时器的程序。 after search in google i found that threading.Timer can help me, i wrote a simple program just for test how threading.Timer work that was this:在谷歌搜索后,我发现 threading.Timer 可以帮助我,我写了一个简单的程序只是为了测试 threading.Timer 是如何工作的:

import threading

def hello():
    print "hello, world"

t = threading.Timer(10.0, hello)
t.start() 
print "Hi"
i=10
i=i+20
print i

this program run correctly.这个程序运行正确。 but when i try to define hello function in a way that give parameter like:但是当我尝试以提供如下参数的方式定义 hello 函数时:

import threading

def hello(s):
    print s

h="hello world"
t = threading.Timer(10.0, hello(h))
t.start() 
print "Hi"
i=10
i=i+20
print i

the out put is :输出是:

hello world
Hi
30
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 726, in run
    self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

i cant understand what is the problem!我不明白是什么问题! can any one help me?谁能帮我?

You just need to put the arguments to hello into a separate item in the function call, like this,你只需要把hello的参数放到函数调用中的一个单独的项目中,就像这样,

t = threading.Timer(10.0, hello, [h])

This is a common approach in Python.这是 Python 中的常用方法。 Otherwise, when you use Timer(10.0, hello(h)) , the result of this function call is passed to Timer , which is None since hello doesn't make an explicit return.否则,当您使用Timer(10.0, hello(h)) ,此函数调用的结果将传递给Timer ,因为hello没有显式返回,所以它是None

An alternative is to use lambda if you want to use normal function parameters.如果您想使用普通函数参数,另一种方法是使用lambda Basically it tells the program that the argument is a function and not to be called on assignment.基本上它告诉程序参数是一个函数,不能在赋值时调用。

t = threading.Timer(10.0, lambda: hello(h))

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

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