Basic use of crontab
foreword
Reference: https://blog.csdn.net/m0_49605975/article/details/120701771
1. Installation
1. Install Crontab with the yum command
yum install vixie-cron
yum install crontabs
2. Start, shut down, restart
/sbin/service crond start #启动服务
/sbin/service crond stop #关闭服务
/sbin/service crond restart #重启服务
/sbin/service crond reload #重新载入配置
3. Set the boot to start
#设置开机启动
systemctl enable crond
#其他指令
systemctl start crond #开启服务
systemctl stop crond #停止服务
systemctl restart crond #重启服务
systemctl disable crond #取消开机启动
2. Basic operation
1. Set the timed task - enter the edit mode - and vim operation one to
crontab -e
2. View the list of scheduled tasks
crontab -l
3. Add a scheduled task
样例: 添加一个定时任务,定时清空某个文件夹里面日志文件的内容
3.1 Write a script to clear filesclean.sh
#!/bin/bash
#author: test
#created time: 2022.03.01
#content: 定时清空/opt/logs路径下sys-info.log文件的内容
#防止启动该脚本失败,添加环境变量
. /etc/profile
. ~/.bash_profile
#内容
cd /opt/logs
> sys-info.log
exit
3.2 Authorize the script
chmod -r+x clean.sh
3.3 Set a scheduled task and execute the script to clear the log regularly
#进入编辑模式,添加以下内容
crontab -e
#30 8 * * * :每天8点30
#. /etc/profile;/bin/sh :添加环境变量,防止脚本启动不成功
#/root/clean.sh :脚本位置
#每天8点30执行这个/root下的clean.sh脚本文件
30 8 * * * . /etc/profile;/bin/sh /root/clean.sh
3.4 Save and exit, restart the crond service
#重启服务
service crond restart
#设置了开机启动可以用下面的重启指令
systemctl restart crond
3.5 Test verification
You can modify the time to a few minutes later than the current time, and test the timing task.
3. How to use scheduled tasks and time format
Use format:时间+指令
* * * * * command
The five asterisks correspond to
* * * * *
分 时 日 月 周
#案例
* * * * * :每分钟
0 8 * * * :每天8点
0 12 * * * :每天12点
0 8 * * 5 :每周星期五 8点
0 12 * * 6 :每周星期六 12点
0 8 10 * * :每个月10号 8点
0 15 15 * * :每个月15号 15点
#案例
0 15 15 * * . /etc/profile;/bin/sh /root/clean.sh #每个月15号 15点定时执行脚本
Crontab time online verification URL: https://tool.lu/crontab