1

自动化运维?看看Python怎样完成自动任务调度⛵ - ShowMeAI

 1 year ago
source link: https://www.cnblogs.com/showmeai/p/16869011.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
033ba1686294138aae8933afa4f31a7e.png

💡 作者:韩信子@ShowMeAI
📘 Python3◉技能提升系列https://www.showmeai.tech/tutorials/56
📘 本文地址https://www.showmeai.tech/article-detail/323
📢 声明:版权所有,转载请联系平台与作者并注明出处
📢 收藏ShowMeAI查看更多精彩内容

ef52563da043349ae0fdec48f8dd6dd1.png

计划任务是几乎每个开发人员都会用到的功能,在服务器上可以用 Cron 作业来进行任务调度,它也是一种稳定的方式。但我们也可以完全程序化,全部使用 Python 来完成调度程序,而且可以有更简单的配置方式。

💡 基于 Python 的任务调度

📌 快速安装与应用

Python工具包 📘schedule可以轻松地在 Python 中进行任务调度,我们可以通过 PyPI 快速安装它。

$ pip install schedule

借助于 schedule,我们几乎可以像用自然语言说话一样快速构建任务计划和时间表。比如,你想每小时运行一次某个功能函数(比如功能是发邮件的函数send_email) ,写法是这样的:

schedule.every().hour.do(send_email)

整个过程非常程序化和自然,完整的一个『构建任务+任务调度』程序如下(我们把每小时发送一次邮件调整为每天一次了)。

import timeimport schedule def send_email(): # 发送邮件的操作可以加在这里 print("Sending email...") schedule.every().day.at("14:45").do(send_email) while True: schedule.run_pending() time.sleep(1)

上面的代码将在每天下午14:45 调用send_email函数。除书写简单易用之外,schedule 工具库还提供了一系列其他功能。

📌 使用装饰器进行调度

我们可以使用装饰器让代码更加干净和优雅。schedule 工具包支持开箱即用的装饰器。我们把上面发送电子邮件的示例改用装饰器完成,代码如下。

import timefrom schedule import repeat, every, run_pending @repeat(every(10).seconds)@repeat(every(5).seconds)def send_email(): # 发送邮件的操作可以加在这里 print("Sending email...") while True: run_pending() time.sleep(1)

上述代码示例中,我们为同一个任务定制了两个计划。第一个将每 10 秒调用一次功能函数,第二个将每 5 秒调用一次。

📌 使用参数运行计划任务

我们有时候会希望任务的调用更灵活一些,比如如果可以通过传递参数来控制任务调度,那就免去了写死各种细节的问题。下面我们把发邮件的任务写成可接受参数的形式:

@repeat(every(10).seconds)@repeat(every(5).seconds, email="[email protected]")def send_email(email="[email protected]"): # 发送邮件的操作可以加在这里 print(f"Sending email...: to {email}")

经过上面的简单处理,我们可以把电子邮箱当作参数传递给调度任务。如果我们希望通过命令行参数给脚本传参,一个示例的代码如下:

import argparse def send_email(email="[email protected]"): # 发送邮件的操作可以加在这里 print(f"Sending email...: to {email}") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-e", "--email", help="Email to send") args = parser.parse_args() if args.email: send_email(args.email) else: send_email()

接下来我们就可以在终端中运行上述脚本,如下所示:

$ python send_mail.py -e [email protected] # 我们也可以使用默认的邮箱参数$ python send_email.py

按计划运行任务是开发过程中的最常见需求之一,系统自带的 Crontab 很好用,但大家也可以试试用 Python 的 schedule 库,让整个代码流程从功能到自动化任务调度都浑然一体。

e9190f41b8de4af38c8a1a0c96f0513b~tplv-k3u1fbpfcp-zoom-1.image

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK