boom
安装 crontab
yum install crontabs
centos7 自带了我没有手动去装
启动 / 关闭
- service crond start // 启动服务
- service crond stop // 关闭服务
- service crond restart // 重启服务
- service crond reload // 重新载入配置
查看 crontab 服务是否已设置为开机启动
systemctl list-unit-files | grep enable | grep crond
将 crontab 加入开机自动启动
- chkconfig crond on
- // 或者
- systemctl enable crond.service
查看 crontab 状态
service crond status // 查看 crontab 服务状态
编写定时任务
命令格式
min hour day month dayofweek command
分 时 天 月 星期几 命令
min: 每个小时的第几分钟执行该任务; 取值范围 0-59
hour: 每天的第几个小时执行该任务; 取值范围 0-23
day: 每月的第几天执行该任务; 取值范围 1-31
month: 每年的第几个月执行该任务; 取值范围 1-12
dayofweek: 每周的第几天执行该任务; 取值范围 0-6,0 表示周末
command: 指定要执行的命令
编辑命令两种方式
在命令行输入: crontab -e 然后添加相应的任务, wq 存盘退出
直接编辑 / etc/crontab 文件, 即 vi /etc/crontab, 添加相应的任务
时间格式
* : 表示任意的时刻; 如小时位 * 则表示每个小时
n : 表示特定的时刻; 如小时位 5 就表示 5 时
n,m : 表示特定的几个时刻; 如小时位 1,10 就表示 1 时和 10 时
n-m : 表示一个时间段; 如小时位 1-5 就表示 1 到 5 点
/n : 表示每隔多少个时间单位执行一次; 如小时位 / 1 就表示每隔 1 个小时执行一次命令, 也可以写成 1-23/1
小栗子
* 1 * * * ~/clear_cache.sh : 从 1:00 到 1:59 每隔 1 分钟执行一次脚本
0 * * * * ~/clear_cache.sh : 每个小时的 0 分钟执行一次脚本
*/10 * * * * ~/clear_cache.sh : 每隔 10 分执行一次脚本
清理系统 cache 的脚本
代码:
- VIM ~/clear_cache_logs.txt
- sudo sysctl -w vm.drop_caches=3
- sudo sysctl -w vm.drop_caches=1
- echo `date -R`>> ~/clear_cache_logs.txt
- free -lh>> ~/clear_cache_logs.txt
清理内存 cache , 并将清理时间和内存剩余情况日志输入到~/clear_cache_logs.txt 文件中, 方便查看, 可以结合 crontab 做定时清理内存 cache 的定时任务.
来源: https://www.cnblogs.com/innerpeacez/p/11212902.html