【问题标题】:Why is the scheduled function never called?为什么从不调用预定函数?
【发布时间】:2015-12-22 06:04:43
【问题描述】:

我有这个非常简单的代码来在后台启动计划任务,但什么都没有打印出来:

def printit():
    print("Hello, World!")


scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(2, 1, printit)
scheduler.run(blocking=False)

while True:
    time.sleep(1)

如果我将阻塞设置为 true,它会起作用。有什么想法吗?

【问题讨论】:

    标签: python python-3.x scheduled-tasks


    【解决方案1】:

    您没有将控制权交给调度程序来安排事件。稍后尝试运行。

    def printit():
    print("Hello, World!")
    
    scheduler = sched.scheduler(time.time, time.sleep)
    scheduler.enter(2, 1, printit)
    
    while True:
        time.sleep(1) # optional to prevent thrash
        scheduler.run(blocking=False)
    

    【讨论】:

    • 您是对的,您的代码有效。但我希望调度器运行一个后台线程并在延时条件满足时执行函数。
    • @suhas-k :要实现您在评论中描述的内容,请使用 threading.Timer()。简单易行。
    • 我有一个更复杂的要求。我曾尝试使用 threading.Timer()。除其他事项外,重新安排时间变得困难。我和 apscheduler 一起去了 - apscheduler.readthedocs.org/en/latest/index.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2019-09-02
    • 2015-04-16
    • 1970-01-01
    • 2021-04-23
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多