python - 带计时器的 Python 线程 - TypeError:“NoneType”对象不可调用
问题描述
我想创建一个小函数,在后台为我的应用程序进行一些获取,所以我希望我的应用程序在调用它之后继续正常执行(所以这应该是非阻塞的)。我希望它每 X 秒在预定线程上运行一次。为此,我有以下内容:
def start(self):
sync_thread = threading.Timer(30, self.readMessages(self.queue, self.client))
sync_thread.start()
其中queue
和client
在__init__
函数中初始化并分配给self
。线程的第一次启动和对我的readMessages
函数的调用运行良好,但目前在 30 秒后我收到以下错误:
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 1254, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable
知道如何处理它,或者有更好的方法吗?
解决方案
你得到了TypeError: 'NoneType' object is not callable
因为threading.Timer
例程试图调用你传递的函数,但是,正如@CherryDT 在评论中提到的那样,你没有传递任何函数,而是传递了readMessage
类中方法的返回值。
你需要做的是:
def MinPrinter:
def __init__(self, xs):
self.xs = xs
def callback(self, xs): # This is your 'readMessages' function
print(min(xs))
def start(self, n):
t = threading.Timer(n, self.callback, args=(self.xs,))
t.start()
mp = MinPrinter([1, 2, 0, 3, -1])
mp.start(30)
# Will print after 30 seconds
-1
参数需要与args
参数一起指定。Optionnaly,您也可以使用参数传递关键字kwargs
参数(需要传递字典)。
推荐阅读
- python - 如何在llvmlite中将c转换为llvm
- php - 在php中的标题字符下按列显示li项目
- c - FFmpeg - 音频编码会在音频上产生额外的噪音
- xml - 构造函数和属性命名空间出现“URI 未注册”错误
- ocaml - 异构列表上的这种类型错误是什么意思?
- c++ - 为什么类型推导失败一次,但在两个非常相似的情况下又成功了一次?
- java - 不同字节数组的相同 BASE64 编码字符串
- javascript - 如何根据屏幕大小更改网页缩放?
- android - 如何在 Android Studio 中使用 FAB 按钮查看新活动
- flutter - Flutter double Fab 在 docker 上的使用