linux 配置定时任务

注意:定时任务执行默认路径,我们配置的命令如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

# the crontab jobs for k8s.
*   * * * * root kube-crontab keep_master_alive
  • 通过执行crontab -e,配置相关的定时任务执行
[root@centos7 ~]# crontab -e
# Puppet Name: hwclock
*/30 * * * * /sbin/hwclock -w
  • 通过在/etc/cron.d增加对应的定时任务
[root@centos7 ~]# cat /etc/cron.d/error-pod-clean
# run cronjob to clean error pod
* * * * * root bash /opt/tools/clean-error-pod.sh >> /var/log/k8s-err-pod.log

[root@SH-IDC1-10-198-34-87 ~]# cat /opt/spe_tools/clean-error-pod.sh
#!/bin/bash
# 清理异常和已经完成的任务
set -e
/usr/local/bin/kubectl get pod -A --field-selector='status.phase==Failed' --output=custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,STATUS:.status.phase,AGE:'.metadata.creationTimestamp'| awk '{print $1" "$2}'  |while read line
do
    namespace=$(echo $line|awk '{print $2}')
    pod_name=$(echo $line|awk '{print $1}')
    pod_info=$(/usr/local/bin/kubectl get pod -n $namespace $pod_name --no-headers)
    pod_status=$(echo $pod_info |awk '{print $3}')
    pod_age=$(echo $pod_info |awk '{print $5}')
    echo "开始删除:$namespace/$pod_name 状态为: $pod_status 持续时间为: $pod_age 的POD"
    /usr/local/bin/kubectl delete pod $pod_name -n $namespace --force --grace-period=0
    echo "删除完成: $namespace/$pod_name"
done

这里如果配置绝对路径很麻烦,我们也可以在脚本中定义执行的命令PATH路径:

#!/bin/bash
# 清理异常和已经完成的任务
set -e
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
kubectl get pod -A --field-selector='status.phase==Failed' --output=custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,STATUS:.status.phase,AGE:'.metadata.creationTimestamp'| awk '{print $1" "$2}'  |while read line
do
    namespace=$(echo $line|awk '{print $2}')
    pod_name=$(echo $line|awk '{print $1}')
    pod_info=$(kubectl get pod -n $namespace $pod_name --no-headers)
    pod_status=$(echo $pod_info |awk '{print $3}')
    pod_age=$(echo $pod_info |awk '{print $5}')
    echo "开始删除:$namespace/$pod_name 状态为: $pod_status 持续时间为: $pod_age 的POD"
    kubectl delete pod $pod_name -n $namespace --force --grace-period=0
    echo "删除完成: $namespace/$pod_name"
done
posted @ 2023-12-29 15:43  yuhaohao  阅读(254)  评论(0编辑  收藏  举报