import os
import time
import subprocess
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
day_log_file = '/root/logdir/info.kongdao.log'
req_count_log_path = '/root/logdir/request/req_count/'
# 定时任务,每天晚上分析当天的日志数据
def log_job():
# 执行shell命令获取当日请求数
req_count_command = 'grep "发起查询请求" ' + day_log_file + ' | wc -l'
req_count_out = subprocess.check_output(req_count_command, shell=True, encoding='UTF-8')
req_count = req_count_out.strip()
# 当天日期
date = str(datetime.date.today())
format_date = date.replace('-', '')
# 获取文件的创建时间
infos = os.stat(day_log_file)
ctime = time.strftime('%Y%m%d', time.localtime(infos.st_ctime))
# request计数存储的文件名
file_name = format_date[:6]
# 若info.kongdao.log不是当天的日志,则当天请求数量为0
if format_date != ctime:
req_count = '0'
req_count_log = date + ' ' + req_count
record_log_command = "echo '" + req_count_log + "' >>" + req_count_log_path + file_name
subprocess.check_output(record_log_command, shell=True, encoding='UTF-8')
if __name__ == '__main__':
sched = BlockingScheduler()
# 每天23:55执行
sched.add_job(log_job, 'cron', hour=23, minute=55)
sched.start()
Python编写定时执行脚本
最新推荐文章于 2024-06-17 14:11:28 发布