前言
參考:https://blog.csdn.net/m0_49605975/article/details/120701771
一、安裝
1.用yum命令安裝Crontab
yum install vixie-cron
yum install crontabs
2.啟動(dòng),關(guān)閉,重啟
/sbin/service crond start #啟動(dòng)服務(wù)
/sbin/service crond stop #關(guān)閉服務(wù)
/sbin/service crond restart #重啟服務(wù)
/sbin/service crond reload #重新載入配置
3.設(shè)置開(kāi)機(jī)啟動(dòng)
#設(shè)置開(kāi)機(jī)啟動(dòng)
systemctl enable crond
#其他指令
systemctl start crond #開(kāi)啟服務(wù)
systemctl stop crond #停止服務(wù)
systemctl restart crond #重啟服務(wù)
systemctl disable crond #取消開(kāi)機(jī)啟動(dòng)
二、基本操作
1.設(shè)置定時(shí)任務(wù)-進(jìn)入編輯模式-和vim操作一至
crontab -e
2.查看定時(shí)任務(wù)列表
crontab -l
3.添加定時(shí)任務(wù)樣例: 添加一個(gè)定時(shí)任務(wù),定時(shí)清空某個(gè)文件夾里面日志文件的內(nèi)容
3.1 編寫(xiě)一個(gè)清除文件的腳本 clean.sh
#!/bin/bash
#author: test
#created time: 2022.03.01
#content: 定時(shí)清空/opt/logs路徑下sys-info.log文件的內(nèi)容
#防止啟動(dòng)該腳本失敗,添加環(huán)境變量
. /etc/profile
. ~/.bash_profile
#內(nèi)容
cd /opt/logs
> sys-info.log
exit
3.2 給腳本授權(quán)
chmod -r+x clean.sh
3.3 設(shè)置定時(shí)任務(wù),定時(shí)執(zhí)行這個(gè)清除日志的腳本
#進(jìn)入編輯模式,添加以下內(nèi)容
crontab -e
#30 8 * * * :每天8點(diǎn)30
#. /etc/profile;/bin/sh :添加環(huán)境變量,防止腳本啟動(dòng)不成功
#/root/clean.sh :腳本位置
#每天8點(diǎn)30執(zhí)行這個(gè)/root下的clean.sh腳本文件
30 8 * * * . /etc/profile;/bin/sh /root/clean.sh
3.4 保存退出,重啟crond服務(wù)
#重啟服務(wù)
service crond restart
#設(shè)置了開(kāi)機(jī)啟動(dòng)可以用下面的重啟指令
systemctl restart crond
3.5 測(cè)試驗(yàn)證
可以修改時(shí)間為當(dāng)前時(shí)間晚幾分鐘,測(cè)試定時(shí)任務(wù)。
三、定時(shí)任務(wù)使用方式,時(shí)間格式
使用格式: 時(shí)間+指令
* * * * * command
五個(gè)星號(hào)分別對(duì)應(yīng)
* * * * *
分 時(shí) 日 月 周
#案例
* * * * * :每分鐘
0 8 * * * :每天8點(diǎn)
0 12 * * * :每天12點(diǎn)
0 8 * * 5 :每周星期五 8點(diǎn)
0 12 * * 6 :每周星期六 12點(diǎn)
0 8 10 * * :每個(gè)月10號(hào) 8點(diǎn)
0 15 15 * * :每個(gè)月15號(hào) 15點(diǎn)
#案例
0 15 15 * * . /etc/profile;/bin/sh /root/clean.sh #每個(gè)月15號(hào) 15點(diǎn)定時(shí)執(zhí)行腳本
Crontab時(shí)間在線驗(yàn)證網(wǎng)址:https://tool.lu/crontab文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-788930.html
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-788930.html
到了這里,關(guān)于Crontab(定時(shí)任務(wù))使用: Linux-Centos7使用crontab制定定時(shí)任務(wù),定時(shí)執(zhí)行某任務(wù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!