任務目標: 在linux 下每隔一個小時執行一次python文件
1. 準備python3程序文件(例如這裏的刷新wxToken 的腳本程序)
主程序: refreshWxTokenTask.py
from logging import handlers
import logging
import configparser
import requests
import os
import time
# 獲取當前路徑
curr_dir = os.path.dirname(os.path.realpath(__file__))
#日誌參數設置
def logInit(curr_dir):
logger = logging.getLogger('test')
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
# 日誌輸出到控制檯
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# 日誌輸出到文件,以時間D(每天)格式劃分
time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=curr_dir+os.sep+'task.log', when='D')
time_rotating_file_handler.setLevel(logging.INFO)
time_rotating_file_handler.setFormatter(formatter)
logger.addHandler(time_rotating_file_handler)
return logger
#日誌初始化
logger=logInit(curr_dir)
# 獲取配置文件參數
# 合成完整路徑
config_file = curr_dir + os.sep + "properties.ini"
cf = configparser.ConfigParser()
cf.read(config_file)
# 獲取[cc]中url對應的值
hostUrl = cf.get("cc-message-web", "url")
tryCount =int(cf.get("cc-message-web", "tryCount"))
logger.info("hosturl: %s",hostUrl)
logger.info("tryCount: %s",tryCount)
rightCode=200
# 請求接口刷新返回結果
def refreshWxToken(url):
try:
r = requests.put(url)
logger.info("request wxtoken result: %s",r.text)
except Exception as e:
logger.error("出現異常: %s",e)
return r
#包含重試次數的接口刷新
def doTaskTry(url,count):
if count>tryCount:
return
time.sleep((count-1)*5)
logger.info("第 %s 次刷新", count)
results=refreshWxToken(url)
if results.status_code== rightCode:
logger.info("刷新成功: %s",results.text)
else:
logger.info("刷新失敗: %s", results.text)
doTaskTry(url,count+1)
# 執行任務總入口
def doTask(url):
doTaskTry(url,1)
doTask(hostUrl)
配置文件程序:properties.ini
[cc-message-web]
url=http://localhost:8080/api/common/refresh/access_token
tryCount=3
上面的URl是對應的刷新token的接口
2. 設置定時任務
7. start.sh 中:
python3 /data/deploy/pythonTask/refreshWxTokenTask.py