0.版本说明
环境:centos7.9
版本:crontabs
1.安装
执行以下命令,查看本机是否已安装crontabs
service crond status
返回结果如下表示已安装
[root@host-10-10-10-14 /]# service crond status
Redirecting to /bin/systemctl status crond.service
● crond.service - Command Scheduler
Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2023-05-30 16:39:55 CST; 5min ago
Main PID: 408 (crond)
CGroup: /system.slice/crond.service
└─408 /usr/sbin/crond -n
May 30 16:39:55 host-10-10-10-14 systemd[1]: Started Command Scheduler.
May 30 16:39:55 host-10-10-10-14 crond[408]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 88% if used.)
May 30 16:39:55 host-10-10-10-14 crond[408]: (CRON) INFO (running with inotify support)
May 30 16:39:55 host-10-10-10-14 crond[408]: (CRON) INFO (@reboot jobs will be run at computer's startup.)
May 30 16:40:01 host-10-10-10-14 crond[408]: /usr/sbin/sendmail: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: N... directory
May 30 16:41:01 host-10-10-10-14 crond[408]: /usr/sbin/sendmail: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: N... directory
May 30 16:42:01 host-10-10-10-14 crond[408]: /usr/sbin/sendmail: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: N... directory
May 30 16:43:01 host-10-10-10-14 crond[408]: (root) RELOAD (/var/spool/cron/root)
Hint: Some lines were ellipsized, use -l to show in full.
如果未安装,执行以下命令安装
yum install vixie-cron crontabs
yum install crontabs
安装完之后,启动crontabs
service crond start
再次执行以下命令查看安装状态
service crond status
设置开机自启动
chkconfig crond on
2.配置定时任务
输入以下命令进行定时任务编辑
crontab -e
输入i进入编辑状态,回车后在第一行输入执行定时任务的代码,按esc退出编辑模式后按:wq保存并退出
1 0 * * * sh /opt/logs/backup.sh
重启crond使改动生效
service crond restart
输入以下命令查看已经添加的任务调度
crontab -l
3.crontab 自定义执行时间
基础格式,定点执行
* * * * * command
格式: | minute | hour | dayofmonth | month | dayofweek | command |
---|---|---|---|---|---|---|
解释: | 分钟 | 小时 | 日期 | 月份 | 周 | 命令 |
范围: | 0-59 | 0-23 | 1-31 | 1-12 | 0-7,0和7都代表周日 | sh /opt/logs/backup.sh |
以下一些例子
每个小时的第30分钟执行
30 * * * * sh /opt/logs/backup.sh
每天12点30分的时候执行
30 12 * * * sh /opt/logs/backup.sh
每月第5天12点30分的时候执行
30 12 5 * * sh /opt/logs/backup.sh
[逗号]代表不连续的时间
每小时的第5,10,15分钟执行
5,10,15 * * * * sh /opt/logs/backup.sh
[-]代表连续的时间范围
每天的5-8小时的20分时执行
20 5-8 * * * sh /opt/logs/backup.sh
*/n 代表每隔多久执行一次
每分钟执行一次
*/1 * * * * sh /opt/logs/backup.sh
4.结束语
本篇只记录自己的学习过程,更好的提升自己