文章目錄
- 一、目的
- 二、方法
- 1.python 版本
- 2.shell 版本
一、目的
我們遇到需要整點自動運行的任務時,使用下面腳本設定自動檢測整點運行的程式,當到達指定的時間時,運行指定的腳本,
二、方法
1.python 版本
代碼如下(示例):
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 14:00:31 2021
@author: dujidan
"""
from subprocess import check_call
from time import sleep
from datetime import datetime, timedelta
while True:
hours_date = (datetime.now()).strftime("%Y%m%d%H")[-2:] # 獲取 時
if hours_date == '08': # 早 8.00
cmd = 'python3 RUN.py'
check_call(cmd, shell=True)
sleep(3600) # 跳過 目標時間段
else:
# sleep 到整點
time_aim = str(datetime.now() + timedelta(hours=1))[:13]+':00:00' # 創建 目標時間
target_time = datetime.strptime(time_aim, '%Y-%m-%d %H:%M:%S') # 格式轉換
delay = (target_time - datetime.now()).total_seconds() # 相減 獲取 差值的秒數
sleep(delay)
2.shell 版本
代碼如下(示例):
band="$( cd "$( dirname "$0" )" && pwd )"
idx=1
while [ $idx != 0 ]
do
clock=`date +"%H"`
if [[ "${clock}" == "10" ]]; then
echo $clock
##sh $band/RUN.sh
fi
if [[ "$clock" == "23" ]];then
sec=`date +%s | awk '{print 1200 - $1 % 1200 + 5;}'` # 加5s 跳過計算+-1的邊界
sleep $sec
else
sec=`date +%s | awk '{print 3600 - $1 % 3600 + 5;}'`
echo $sec
sleep $sec
fi
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/246560.html
標籤:python
