计划运行作业直到某个时间

2024-03-29 06:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,先谢谢你。我正在尝试编写简单的代码,以便在指定的持续时间内运行函数。我基本上是从schedule模块文档(只是更改了单位)中复制了这个逐字记录,但由于某些原因,它无法正常工作

import schedule
from datetime import datetime, timedelta, time

def job():
    print('Hello World')

schedule.every(5).seconds.until(timedelta(seconds=20)).do(job)
    

我没有收到任何错误,但控制台不会打印“Hello World”。它必须是一些简单的东西,但我不能弄明白,因为我在这方面是非常新的


Tags: 模块函数代码文档importhelloworlddatetime
1条回答
网友
1楼 · 发布于 2024-03-29 06:41:32

使用schedule时,需要一个while循环来保持程序运行。这样修改代码将解决问题

import schedule
from datetime import datetime, timedelta, time
import time


def job():
    print('Hello World')


schedule.every(5).seconds.until(timedelta(seconds=20)).do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

相关问题 更多 >