Linux中,周期執行的任務一般由crond這個守護進程來處理。cron讀取一個或多個配置文件,這些配置文件中包含了命令行及其調用時間。crond的配置文件稱為“crontab”,是“cron table”的簡寫。
一、crond服務 -- crontab
查看cron服務狀態
[root@VM_138_80_centos Home]# sudo service crond status
crond (pid 29349) is running...
開啟cron服務
[root@VM_138_80_centos Home]# sudo service crond start
Starting crond: [ OK ]
關閉cron服務
[root@VM_138_80_centos Home]# sudo service crond stop
Stopping crond: [ OK ]
重啟cron服務
[root@VM_138_80_centos Home]# sudo service crond restart
Stopping crond: [ OK ]
Starting crond: [ OK ]
二、crontab服務用法
- crontab –e : 修改 crontab 文件,如果文件不存在會自動創建。
- crontab –l : 顯示 crontab 文件。
- crontab -r : 刪除 crontab 文件。
- crontab -ir : 刪除 crontab 文件前提醒用戶。
在crontab文件中寫入需要執行的命令和時間,該文件中每行都包括六個域,其中前五個域是指定命令被執行的時間,最后一個域是要被執行的命令。每個域之間使用空格或者制表符分隔。
格式如下:
minute hour day-of-month month-of-year day-of-week commands
合法值為:00-59 00-23 01-31 01-12 0-6 (0 is sunday)
除了數字還有幾個特殊的符號:"*"、"/"和"-"、","
- *代表所有的取值范圍內的數字
- "/"代表每的意思,"/5"表示每5個單位
- "-"代表從某個數字到某個數字
- ","分開幾個離散的數字
注:commands 注意以下幾點
- 要是存在文件,要寫絕對路徑
- 即使是打印也不會顯示在顯示屏,在后台運行,最好重定向日志
三、實戰演練
運行crontab -e命令,在文本中寫入
例如:每天早上6點清理前天的日志文件
0 6 * * * 清理日志命令或執行腳本
清理日志命令或執行腳本修改為你想執行的操作,我這里寫入"python /root/scripts/time_clear_ireader_logs.py"
然后進行保存退出,使用crontab -l 進行查看定時任務,看下面的第三條。
[root@VM_138_80_centos Home]# crontab -l
*/1 * * * * /usr/local/qcloud/stargate/admin/start.sh > /dev/null 2>&1 &
*/20 * * * * /usr/sbin/ntpdate ntpupdate.tencentyun.com >/dev/null &
0 6 * * * "python /root/scripts/time_clear_ireader_logs.py"
四、Python清理腳本
腳本中有配置內容,可按需修改
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# import math, os, sys, time
import traceback
import subprocess
import datetime
# 定時任務腳本,刪除歸檔日志文件
# 定義前兩天的時間
the_day_before_yesterday = (datetime.date.today() + datetime.timedelta(-2)).strftime('%y_%m_%d')
# 定義文件路徑
logs_file_Path = {
"/data/Home/Logs/": "刪除用戶端歸檔日志文件[Home]",
"/data/Admin/Logs/": "刪除管理員端歸檔日志文件[Admin]",
}
# 清除大於1G的文件
def clear_tomcat_archive_logs():
print("<---刪除tomcat歸檔日志文件--->")
for file_path, message in logs_file_Path.items():
linux_command = "rm -rf " + file_path + "*" + the_day_before_yesterday + "*"
response_message, response_code = execute_shell(linux_command)
check_result(int(response_code), message)
print("<---刪除tomcat歸檔日志文件--->")
# 執行linux命令獲取返回結果與返回碼
def execute_shell(command, print_output=True, universal_newlines=True):
print("需要執行的linux命令為[" + command + "]")
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
universal_newlines=universal_newlines)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
errout = p.stderr.read()
p.stdout.close()
p.stderr.close()
return str(output), str(p.returncode)
# 判斷運行結果
def check_result(result, message):
if result == 0:
print(message + "執行成功")
else:
print(message + "執行失敗")
# 異常的處理
def print_excption(e):
print("<---The Excption Begin--->")
print('\n' * 1)
traceback.print_exc()
print('\n' * 1)
print("<---The Excption End--->")
# 最終執行的方法
def final_execute():
print("<---The time_clear_ireader_logs.py Begin,the time is [" + datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S') + "]--->")
print('\n' * 1)
try:
clear_tomcat_archive_logs()
except Exception as e:
print_excption(e)
print('\n' * 1)
print("<---The time_clear_ireader_logs.py End,the time is [" + datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S') + "]--->")
if __name__ == '__main__':
# 最終執行
final_execute()