目录
简介
如果需要在主机定时或周期启动或运行某一程序或脚本,由于程序或脚本运行的时长并不确定,可能会出现同时重复运行多个该程序或脚本的情况。
安装
CentOS
yuminstall vixie-cron crontabs //安装Crontab
chkconfigcrondon //设为开机自启动
service crondstart //启动
说明:vixie-cron软件包是cron的主程序;crontabs软件包是用来安装、卸装、 或列举用来驱动 cron 守护进程的表格的程序。
Debian
apt-getinstallcron //大部分情况下Debian都已安装。
/etc/init.d/cronrestart //重启Crontab
定时任务目录
目录路径 | 执行说明 |
---|---|
/etc/cron.hourly | 系统定时任务周期每小时执行该目录下的脚本 |
/etc/cron.daily | 系统定时任务周期每一天执行该目录下的脚本 |
/etc/cron.weekly | 系统定时任务周期每一周执行该目录下的脚本 |
/etc/cron.monthly | 系统定时任务周期每个月执行该目录下的脚本 |
注意权限
注意:增加.sh脚本可执行权限
chmod +x ******.sh
定时任务文件
类型 | 路径 |
---|---|
全局定时任务配置文件 | /etc/crontab |
用户定时任务配置文件 | /var/spool/cron/root |
定时任务有种
语法
基本格式 | |||||
---|---|---|---|---|---|
* | * | * | * | * | command |
分(0-59) | 时(0-23) | 日(1-31) | 月(1-12) | 周(0-6) | 定时执行的命令 |
命令
# 设定某个用户的cron服务
crontab -u
# 查看定时任务
crontab -l
# 设置定时任务
crontab -e
# 删除定时任务
crontab -r
# 查看帮助
crontab -h
# 例如:root查看自己的cron设置
crontab -u root -l
# 例如:root想删除fred的cron设置
crontab -u fred -r
# 关闭crontab服务
systemctl stop crond
# 开启crontab服务
systemctl start crond
# 重启crontab服务
systemctl restart crond
# 查看crontab服务
systemctl status crond
# 重新载入crontab配置
systemctl reload crond
示例
修改定时任务配置文件
# 每天15:30运行一个python脚本:
30 17 * * * root python -u script.py > /dev/null
# 每天凌晨3:00执行备份程序:
0 3 * * * /root/backup.sh
# 每周日8点30分执行日志清理程序:
30 8 * * 7 /root/clear.sh
# 每周1周5 0点整执行test程序:
0 0 ** 1,5 test
# 每年的5月12日14点执行wenchuan程序:
0 14 12 5 * /root/wenchuan
补充
在实际的使用过程中可能会存在着重复启动定时程序的可能,需要对定时任务进一步改进。
flock通常会使用一个「锁文件」,也就是建立一个文件来告诉别的进程自己在运行,如果检测到那个文件存在,则认为有操作同样数据的进程在工作,这样就可以防止其它进程访问这个文件。
flock -xn /tmp/tmp.lock
改进后的形式:
# 保证同时只有一个程序运行
*/5 * * * * root flock -xn /tmp/tmp.lock python -u DownLoad.py > /dev/null
参数
Crontabhttps://link.zhihu.com/?target=https%3A//blog.csdn.net/bandaoyu/article/details/122623607linux Crontab的安装
https://www.dandelioncloud.cn/article/details/1531152954367426561