如何使用python中的计划包计划在中部时间晚上8点运行作业 [英] How schedule a job run at 8 PM CET using schedule package in python
问题描述
我想安排一个Python脚本在CET的每个工作日(星期一至星期五)运行.该怎么做.
I want to schedule a python script to run at every workday (monday to friday) at 8 PM CET. How can this be done.
import schedule
import time
def task():
print("Job Running")
schedule.every(10).minutes.do(task)
这怎么办?
推荐答案
是否存在无法使用crontab或Windows Task Scheduler计划作业的原因?
答案一:
schedule
模块文档没有指出安排python脚本在CET的每个工作日(星期一至星期五)运行的简单方法.
The schedule
module documentation does not indicate a simple way to schedule a python script to run every workday (monday to friday) at 8 PM CET.
此外,schedule
模块不支持使用时区.
参考: 4.1.3计划是否支持时区?
Plus the use of timezones is not supported in the schedule
module.
Reference: 4.1.3 Does schedule support timezones?
以下是使用schedule
模块安排作业在每个工作日20:00(晚上8点)运行的方法.
Here is way to schedule a job to run every workday at 20:00 (8pm) using the schedule
module.
import schedule
import time
def schedule_actions():
# Every Monday task() is called at 20:00
schedule.every().monday.at('20:00').do(task)
# Every Tuesday task() is called at 20:00
schedule.every().tuesday.at('20:00').do(task)
# Every Wednesday task() is called at 20:00
schedule.every().wednesday.at('20:00').do(task)
# Every Thursday task() is called at 20:00
schedule.every().thursday.at('20:00').do(task)
# Every Friday task() is called at 20:00
schedule.every().friday.at('20:00').do(task)
# Checks whether a scheduled task is pending to run or not
while True:
schedule.run_pending()
time.sleep(1)
def task():
print("Job Running")
schedule_actions()
答案二:
我花了一些额外的时间在python脚本中使用调度程序.在研究过程中,我发现了Python库-Advanced Python Scheduler(APScheduler
).
基于模块的文档.
I spent some additional time looking at using a scheduler inside a python script. During my research, I discovered the Python library -- Advanced Python Scheduler (APScheduler
).
This library seems to be very flexible based on the module's documentation.
这是我为您整理的一个示例,该示例在我的测试中起作用.
Here is an example that I put together for you, which worked in my testing.
from apscheduler.schedulers.background import BlockingScheduler
# BlockingScheduler: use when the scheduler is the only thing running in your process
scheduler = BlockingScheduler()
# Other scheduler types are listed here:
# https://apscheduler.readthedocs.io/en/latest/userguide.html
# Define the function that is to be executed
# at a scheduled time
def job_function ():
print ('text')
# Schedules the job_function to be executed Monday through Friday at 20:00 (8pm)
scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour=20, minute=00)
# If you desire an end_date use this
# scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour=20, minute=00, end_date='2019-12-31')
# Start the scheduler
scheduler.start()
这篇关于如何使用python中的计划包计划在中部时间晚上8点运行作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!