Linux 定时任务配置指南
提示:在定时任务中执行命令时,由于默认环境变量 PATH 的限制,需要使用绝对路径。例如 kubectl 命令应写为 /usr/local/bin/kubectl,或者在脚本开头全局声明 PATH 变量。
配置方式
在 Linux 系统中,配置定时任务主要有以下三种常用方法:
方法一:直接编辑 /etc/crontab 文件
[root@centos7 ~]# cat /etc/crontab
SHELL="/bin/bash"
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
MAILTO=""
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
# 定时清理过期的容器编排任务
* * * * * root kube-crontab sync_cluster_state
方法二:使用 crontab -e 命令编辑
[root@centos7 ~]# crontab -e
# 同步系统时间
*/30 * * * * /usr/sbin/hwclock -w
方法三:在 /etc/cron.d 目录创建任务文件
[root@centos7 ~]# cat /etc/cron.d/failed-pod-reaper
# 定期清理失败状态的 Pod 资源
* * * * * root bash /opt/scripts/purge-failed-pods.sh >> /var/log/k8s-pod-cleanup.log
[root@SH-IDC1-10-198-34-87 ~]# cat /opt/scripts/purge-failed-pods.sh
#!/bin/bash
# 自动清理异常终止的 Pod 对象
set -e
TARGET_PODS=$(/usr/local/bin/kubectl get pod -A --field-selector='status.phase==Failed' -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase --no-headers)
echo "$TARGET_PODS" | while read -r ns pod_name pod_state; do
if [[ -n "$ns" && -n "$pod_name" ]]; then
pod_details=$(/usr/local/bin/kubectl get pod "$pod_name" -n "$ns" -o jsonpath='{.status.phase} {.metadata.creationTimestamp}')
echo "即将清理命名空间 [$ns] 中的失败 Pod: $pod_name (状态: $pod_state)"
/usr/local/bin/kubectl delete pod "$pod_name" -n "$ns" --force --grace-period=0
echo "已成功清理: $ns/$pod_name"
fi
done
如果觉得每次写绝对路径过于繁琐,也可以在脚本开头预先定义 PATH 环境变量:
#!/bin/bash
# 自动清理异常终止的 Pod 对象
set -e
# 声明可执行程序路径
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
TARGET_PODS=$(kubectl get pod -A --field-selector='status.phase==Failed' -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase --no-headers)
echo "$TARGET_PODS" | while read -r ns pod_name pod_state; do
if [[ -n "$ns" && -n "$pod_name" ]]; then
pod_details=$(kubectl get pod "$pod_name" -n "$ns" -o jsonpath='{.status.phase} {.metadata.creationTimestamp}')
echo "即将清理命名空间 [$ns] 中的失败 Pod: $pod_name (状态: $pod_state)"
kubectl delete pod "$pod_name" -n "$ns" --force --grace-period=0
echo "已成功清理: $ns/$pod_name"
fi
done