Python定时器未按预期等待

3 投票
2 回答
998 浏览
提问于 2025-04-17 21:04

我有一段代码:

t = threading.Timer(570.0, reddit_post(newmsg))
t.start()

这段代码是用来快速发一个Reddit帖子。可惜的是,它并没有等570秒,而是直接执行了reddit_post,根本没有等到。

我该怎么做才能修复这个问题呢?

2 个回答

5

这是因为你实际上是在调用这个函数,而不是把参数传递给Timer类。当你写t = threading.Timer(570.0, reddit_post(newmsg))的时候,你已经执行了这个函数。

你需要做的是这样:

threading.Timer(570.0, reddit_post, [newmsg]).start()

可以参考一下Timer类的文档

1

更详细地说:

当你使用 Timer 这个构造函数时,你需要提供三个参数。第一个参数是你希望计时器等待多长时间。第二个参数应该是一个可调用的对象(比如一个函数)。第三个参数是一个列表,里面放的是用来调用这个函数的参数。

举个例子。

# First we define a function to call.
def say_hello(name):
    print('hello ' + name)

# Now we can call this function.
say_hello('john')

# But when we make a timer to call it later, we do not call the function.
timer = threading.Timer(10, say_hello, ['john'])
timer.start()

撰写回答