我想安排一个python脚本在每个工作日(星期一到星期五)在晚上8点CET运行。怎么能做到这一点。
import schedule
import time
def task():
print("Job Running")
schedule.every(10).minutes.do(task)怎么能做到这一点。
发布于 2019-04-02 03:34:21
是否有理由不能使用crontab或Windows任务计划程序来安排作业?
答一:
schedule模块文档没有指明一种简单的方法来安排python脚本在晚上8点运行每个工作日(周一到周五)。
另外,schedule模块不支持使用时区。
参考资料:4.1.3时间表是否支持时区?
下面是使用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库--高级Python (APScheduler)。
基于模块的文档。,这个库看起来非常灵活
这里有一个我为大家提供的例子,它在我的测试中起了作用。
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()https://stackoverflow.com/questions/55466212
复制相似问题