【发布时间】:2025-12-17 08:45:01
【问题描述】:
所以,我有这个代码:
t = threading.Timer(570.0, reddit_post(newmsg))
t.start()
开始一个快速的 Reddit 帖子。遗憾的是,它没有等待 570 秒,而是自动执行 reddit_post 而无需实际等待。
我能做些什么来解决这个问题?
【问题讨论】:
标签: python multithreading timer
所以,我有这个代码:
t = threading.Timer(570.0, reddit_post(newmsg))
t.start()
开始一个快速的 Reddit 帖子。遗憾的是,它没有等待 570 秒,而是自动执行 reddit_post 而无需实际等待。
我能做些什么来解决这个问题?
【问题讨论】:
标签: python multithreading timer
那是因为当你说t = threading.Timer(570.0, reddit_post(newmsg)) 时,你实际上是在调用函数,而不是将参数传递给Timer 类
你需要做的是:
threading.Timer(570.0, reddit_post, [newmsg]).start()
【讨论】:
更详细的解释:
当你调用 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()
【讨论】: