在Python3中安排事件

时间:2020-07-27 08:22:37

标签: python python-3.x scheduled-tasks

我有4个python脚本,大部分都是从命令行运行的。我一直在尝试安排它们的时间,但是到目前为止,我还没有找到一种好的方法。我对这一切应该如何工作有一些要求。

我的脚本及其作用:

脚本编号1 ;从数据库中扫描大量记录并进行一些处理。

脚本编号2 ;是否只在脚本编号1完成后才执行 的更多处理

脚本编号3&4 ;这些脚本与1或2无关,但应每小时运行一次。

有人建议用Python安排这些脚本的最佳方法是什么?

3 个答案:

答案 0 :(得分:0)

我了解所需的工作需要安排。 对于计划作业,最好使用Jenkins之类的CI工具。

  1. 为脚本1和2做一份工作,并在完成脚本1之后运行脚本2。
  2. 为每小时运行的脚本3和4分别做两项工作。

答案 1 :(得分:0)

有一个很好的框架来计划python(不仅是python!)脚本! 看看:https://github.com/spotify/luigi 它在github上已经有13,000个star,在许多公司的产品中都使用过,有很多教程。它由Spotify开发和支持,因此正在积极更新。而且,当然是开源的:)

用户可以通过以下方式通过PyPi轻松安装它:

pip install luigi

如果您愿意,它甚至还具有Web-GUI。 我真的推荐它!

答案 2 :(得分:0)

如果您想使用Python,可以使用apscheduler。 不必单独运行脚本,而可以导入它们并运行其功能。

示例:

import time
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()

# your script 1 main function (should be imported instead of creating here)
def my_script1():
    pass

# your script 2 main function (should be imported instead of creating here)
def my_script2():
    pass


# This exists so 
def my_script_runner():
    my_script1()
    my_script2()

# your script 3 main function (should be imported instead of creating here)
def my_script3(id=None):
    print(id)

job_kwargs = {
    'id': 1
}

# Hourly job

scheduler.add_job(my_script_runner, 'interval', [], None, name='myscripts1and2', seconds=7200)

scheduler.add_job(fn, 'interval', [], job_kwargs, name='myscript3', seconds=3600)
scheduler.start()


# Main executer loop
try:
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()
相关问题