python - 如何使用 BlockingScheduler 每 10 分钟运行一次任务 5 秒?

标签 python cron

我试图每 10 分钟运行一次任务,例如 5 点,13:15、13:25,...

但是,它不起作用。

该功能每小时仅运行一次,即中午 12 点至下午 4 点。

sched.add_job(run_batch, 'cron', day_of_week='mon-fri', 小时='12-16', 分钟='5,15,25,35,45,55', timezone= '美国/芝加哥')

最佳答案

问题标题表明您正在使用 Python 库的 BlockingScheduler 函数 - Advanced Python Scheduler ( APScheduler )。

根据您的问题,您希望在周一到周五的 1200 到 1600 之间在 Python 脚本中运行 cron 作业。您希望该作业在 12:05、12:15、12:25 等运行。

我还没有完全测试下面的答案,但我确实运行了 1 个小时的测试(从今天早上 8 点开始),并且它在 8:05、8:15、8:25、8:35、8 正确触发: 45、8:55 和 9:05。

我使用 start_date 变量在精确的日期和时间启动调度程序。

from datetime import datetime
from apscheduler.schedulers.background import BlockingScheduler

# BlockingScheduler: use when the scheduler is the only thing running in your process
scheduler = BlockingScheduler()

# Define the function that is to be executed
# at a scheduled time
def job_function():
    print(datetime.now().time().strftime('%H:%M'))

# Schedules the job_function to be executed Monday through Friday at between 12-16 at specific times.   
scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour='12-16', minute='5,15,25,35,45,55', start_date='2021-03-23 12:00:00', timezone='America/Chicago')

# Start the scheduler
scheduler.start()

顺便说一句,您可以替换这些时间间隔。

minute='5,15,25,35,45,55'

用这个,我测试过。

minute='5-55/10'

只是一个附带问题。您是否考虑过使用 UTC 而不是中部时间?

from datetime import datetime
from apscheduler.schedulers.background import BlockingScheduler

# BlockingScheduler: use when the scheduler is the only thing running in your process
scheduler = BlockingScheduler()

# Define the function that is to be executed
# at a scheduled time
def job_function():
    print(datetime.utcnow().strftime('%H:%M'))

# Schedules the job_function to be executed Monday through Friday at between 12-16 at specific times.   
scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour='17-21', minute='5-55/10', start_date='2021-03-23 12:00:00', timezone='UTC')

# Start the scheduler
scheduler.start()

如果您对此代码有任何问题,请告诉我,我会为您进行调查。

关于python - 如何使用 BlockingScheduler 每 10 分钟运行一次任务 5 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66662408/

相关文章:

python - 如何使用 bool 值重命名和替换列中的值?

Python 网页抓取 : how to skip url error

linux - cron 脚本已执行但没有输出

google-app-engine - Google App Engine 上的 Cron 作业

linux - 从 plesk 运行 cronjobs

python - Jupyter Notebook 中的交互式 Bokeh 图未更新

python - 无法触发颜色上的鼠标按下事件

Python - While 假循环

ssl - Cyber​​Panel SSL 自动更新

javascript - node.js 中的 Cronjobs