请求理解crontab条目并将Unix定时脚本转换为Python
原Unix定时任务解析
定时规则部分 (1 17-23 * * *)
- 第1位(分钟):
1→ 每小时的第1分钟执行 - 第2位(小时):
17-23→ 每天17点到23点(即下午5点到晚上11点)的每个小时 - 第3-5位(日、月、星期):
*→ 任意日期、任意月份、任意星期几都执行
→ 总结:每天下午5:01、6:01、…、11:01各执行一次
执行命令部分 (curl ...)
这是一个HTTP PUT请求,作用是向指定设备发送配置指令:
- 请求目标地址:
http://192.168.1.70:80/api/v2/configurations - 身份验证头:
Auth-Token: 512532eb-0d57-4a59-8da0-e1e136945ee8 - 提交数据:
EM_OperatingMode=10(将设备运行模式设置为10)
Python实现代码
方案1:使用schedule库(轻量简单)
先安装依赖:
pip install requests schedule
代码:
import requests import schedule import time def send_config_request(): url = "http://192.168.1.70:80/api/v2/configurations" headers = {"Auth-Token": "512532eb-0d57-4a59-8da0-e1e136945ee8"} data = {"EM_OperatingMode": "10"} try: response = requests.put(url, headers=headers, data=data) response.raise_for_status() print(f"配置发送成功,状态码:{response.status_code}") except requests.exceptions.RequestException as e: print(f"配置发送失败:{str(e)}") # 按原定时规则设置任务 for hour in range(17, 24): schedule.every().day.at(f"{hour}:01").do(send_config_request) # 保持程序运行以触发任务 while True: schedule.run_pending() time.sleep(60)
方案2:使用APScheduler库(更健壮,支持复杂调度)
先安装依赖:
pip install requests apscheduler
代码:
from apscheduler.schedulers.blocking import BlockingScheduler import requests def send_config_request(): url = "http://192.168.1.70:80/api/v2/configurations" headers = {"Auth-Token": "512532eb-0d57-4a59-8da0-e1e136945ee8"} data = {"EM_OperatingMode": "10"} try: response = requests.put(url, headers=headers, data=data) response.raise_for_status() print(f"配置发送成功,状态码:{response.status_code}") except requests.exceptions.RequestException as e: print(f"配置发送失败:{str(e)}") # 创建调度器并添加任务(完全匹配原cron规则) scheduler = BlockingScheduler() scheduler.add_job(send_config_request, 'cron', minute=1, hour='17-23') try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown()
内容的提问来源于stack exchange,提问作者alla fine moriremo tutti
相关产品推荐
相关产品推荐

