简介

如果需要在主机定时或周期启动或运行某一程序或脚本,由于程序或脚本运行的时长并不确定,可能会出现同时重复运行多个该程序或脚本的情况。

安装

CentOS

1
2
3
yuminstall vixie-cron crontabs //安装Crontab
chkconfigcrondon //设为开机自启动
service crondstart //启动

Debian(注:平时直接用以下/etc… 中的cron命令)

1
2
apt-getinstall cron //大部分情况下Debian都已安装。
/etc/init.d/cron restart //重启Crontab

定时任务目录

目录路径 执行说明
/etc/cron.hourly 系统定时任务周期每小时执行该目录下的脚本
/etc/cron.daily 系统定时任务周期每一天执行该目录下的脚本
/etc/cron.weekly 系统定时任务周期每一周执行该目录下的脚本
/etc/cron.monthly 系统定时任务周期每个月执行该目录下的脚本

注意权限

注意:增加.sh脚本可执行权限

1
chmod +x ******.sh

定时任务文件

类型 路径
全局定时任务配置文件 /etc/crontab
用户定时任务配置文件 /var/spool/cron/root

语法

基本格式
* * * * * command
分(0-59) 时(0-23) 日(1-31) 月(1-12) 周(0-6) 定时执行的命令

命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 设定某个用户的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

示例

修改定时任务配置文件

1
2
3
4
5
6
7
8
9
10
# 每天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通常会使用一个「锁文件」,也就是建立一个文件来告诉别的进程自己在运行,如果检测到那个文件存在,则认为有操作同样数据的进程在工作,这样就可以防止其它进程访问这个文件。

1
flock -xn /tmp/tmp.lock

改进后的形式:

1
2
# 保证同时只有一个程序运行
*/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/122623607

linux Crontab的安装https://www.dandelioncloud.cn/article/details/1531152954367426561


相关链接(侵删)

  1. 定时任务——Crontab
  2. linux 怎么定时去执行一个 .sh 文件
  3. (相对详细)Linux新建定时任务crontab
  4. 【Linux】23.ubuntu定时执行脚本/etc/crontab 和 定时任务不执行的解决办法
  5. 【运维知识基础篇】Linux定时任务

=================我是分割线=================

欢迎到公众号来唠嗑: