【问题标题】:Python timer not waiting as expectedPython计时器未按预期等待
【发布时间】:2025-12-17 08:45:01
【问题描述】:

所以,我有这个代码:

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

开始一个快速的 Reddit 帖子。遗憾的是,它没有等待 570 秒,而是自动执行 reddit_post 而无需实际等待。

我能做些什么来解决这个问题?

【问题讨论】:

    标签: python multithreading timer


    【解决方案1】:

    那是因为当你说t = threading.Timer(570.0, reddit_post(newmsg)) 时,你实际上是在调用函数,而不是将参数传递给Timer

    你需要做的是:

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

    参考documentation of the Timer class

    【讨论】:

    • 那我该怎么做才能不调用这个函数呢?
    • 不能用 sleep 来拖延吗?
    • @abhiii5459 sleep 将使当前线程进入睡眠状态,而不是您想要延迟的线程。这不是 OP 想要的。
    • 哦,好的,是的。我的错!
    【解决方案2】:

    更详细的解释:

    当你调用 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()
    

    【讨论】: