首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python中的调度包在晚上8点运行作业

如何使用python中的调度包在晚上8点运行作业
EN

Stack Overflow用户
提问于 2019-04-02 02:44:24
回答 1查看 2.6K关注 0票数 0

我想安排一个python脚本在每个工作日(星期一到星期五)在晚上8点CET运行。怎么能做到这一点。

代码语言:javascript
复制
   import schedule
    import time

    def task():
        print("Job Running")

    schedule.every(10).minutes.do(task)

怎么能做到这一点。

EN

回答 1

Stack Overflow用户

发布于 2019-04-02 03:34:21

是否有理由不能使用crontab或Windows任务计划程序来安排作业?

答一:

schedule模块文档没有指明一种简单的方法来安排python脚本在晚上8点运行每个工作日(周一到周五)。

另外,schedule模块不支持使用时区。

参考资料:4.1.3时间表是否支持时区?

下面是使用schedule模块安排作业在20:00 (晚上8点)运行每个工作日的方法。

代码语言:javascript
复制
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)。

基于模块的文档。,这个库看起来非常灵活

这里有一个我为大家提供的例子,它在我的测试中起了作用。

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55466212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档