我想安排一个Python脚本在CET CET的每个工作日(周一至周五)运行。该怎么做。
import schedule
import time
def task():
print("Job Running")
schedule.every(10).minutes.do(task)
这怎么办?
答案 0 :(得分:1)
您是否有理由无法使用crontab或Windows Task Scheduler来计划您的工作?
答案一:
schedule
模块文档没有指出安排python脚本在CET CET的每个工作日(星期一至星期五)运行的简单方法。
此外,schedule
模块中不支持使用时区。
参考:4.1.3 Does schedule support timezones?
这里是一种使用schedule
模块来安排作业在每个工作日20:00(晚上8点)运行的方法。
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
)。
基于模块的documentation.
这是我为您整理的一个示例,该示例在我的测试中起作用。
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()