首页 > 解决方案 > 带计时器的 Python 线程 - TypeError:“NoneType”对象不可调用

问题描述

我想创建一个小函数,在后台为我的应用程序进行一些获取,所以我希望我的应用程序在调用它之后继续正常执行(所以这应该是非阻塞的)。我希望它每 X 秒在预定线程上运行一次。为此,我有以下内容:

    def start(self): 
        sync_thread = threading.Timer(30, self.readMessages(self.queue, self.client))
        sync_thread.start()

其中queueclient__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

知道如何处理它,或者有更好的方法吗?

标签: pythonmultithreading

解决方案


你得到了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参数(需要传递字典)。


推荐阅读