在java开发时,常常使用Quartz 来作为定时任务调度,当然也有分布式调度任务系统如开源的分布式任务调度系统xxl-job,
那么在Linux怎么定时调度任务呢?这个有crontab 神命令。
学习该命令,首先得知道man 命令

man 手册

man 该指令偏手册,如man xx 会列出xx命令的使用手册,和xx -help 指导性命令效果差不多

背景

在项目开发时,需要为es产生的日志写一个定时任务脚本

0 1 * * * /home/clean_es_index/clean_es_script.sh > /dev/null 2>&1

说明

/dev/null : 在类Unix系统中,/dev/null,或称空设备,是一个特殊的设备文件,它丢弃一切写入其中的数据(但报告写入操作成功),读取它则会立即得到一个EOF。
Linux的设备会以目录的形式挂载到主机上
至于 2>&1 这命令请查看本栏目的 Linux里的2>&1究竟是什么:https://blog.csdn.net/u014229282/article/details/81070862

清理文件定时任务

clean_es_script.sh 该脚本清理es产生的数据,仅清理一个月前得文件

!/bin/bash

清理elasticsearch index,仅保存一个月数据

last_month=date -d "last month" +"%Y.%m"

last_month_curr_day=date -d "last month" +"%Y.%m.%d"

curr_month=date +"%Y.%m"

curr_month_last_day=date -d "$(date -d "1 month" +"%Y%m01") -1 day" +"%Y.%m.%d"

curr_day=date +"%Y.%m.%d"

log_dir="/home/clean_es_index"

打印日志

function print_log {

  echo -e "\n[(date '+%Y-%m-%d %H:%M:%S')]" @ >> {log_dir}/{curr_month}.log

}

//清理上个月当天的Index

print_log "清理开始,正在执行curl -XDELETE" "localhost:9200/logstash-*-${last_month_curr_day}"

curl -XDELETE "localhost:9200/logstash-*-{last_month_curr_day}" >> {log_dir}/${curr_month}.log

如果今天是本月最后一天,删除上个月所有的index

if [ {curr_day} = {curr_month_last_day} ]; then

  print_log "最后一天,正在执行curl -XDELETE" "localhost:9200/logstash--${last_month}."

  curl -XDELETE "localhost:9200/logstash--${last_month}." >> {log_dir}/{curr_month}.log

fi

print_log "清理结束"


本文章来源:https://github.com/Zeb-D/my-review

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐