序言
首先,先认识crond服务,crond是linux下用来周期性的执行某种任务或等待处理某些事件,cron进程每分钟会定期检查是否有要执行的任务,如果有要执行的任务,则自动执行该任务。
一、安装,上篇博客有提到配置yum源 示例:
yum源配置:
1.备份原软件源
sudo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
2.添加CentOS 7软件源
sudo curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
3.生成本地缓存,加快搜索、安装软件的速度
sudo yum clean all && sudo yum makecache
4.查看软件源是否添加成功
sudo yum repolist
安装linux一般选择最小化安装:
最小化安装缺失补充
yum -y install perl.x86_64
yum install -y libaio.x86_64
yum -y install net-tools.x86_64
一般linux上已经安装了crond,如果没有安装可以用下面命令进行安装:
yum -y install vixie-cron
yum -y install crontabs
说明:
vixie-cron 软件包是 cron 的主程序;
crontabs 软件包是用来安装、卸装、或列举用来驱动 cron 守护进程的表格的程序。
二、配置
cron是linux的内置服务,可以用以下方法操作这个服务:
#启动服务
service crond start
#关闭服务
service crond stop
#重启服务
service crond restart
#查看crontab服务状态
service crond status
在CentOS系统中加入开机自动启动:
chkconfig --level 345 crond on
你也可以将这个服务在系统启动的时候自动启动:
在/etc/rc.d/rc.local这个脚本的末尾加上:
/sbin/service crond start
三、crontab
cron服务提供crontab命令来设定cron服务的,以下是这个命令的一些参数与说明:
usage:crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
-e(edit user’s crontab)
-l(list user’s crontab)
-r(delete user’s crontab)
例子:root查看darcy的cron设置:crontab -u darcy -l
在编辑cron服务时,编辑的内容有一些格式和约定,输入:crontab -e 进入vi编辑模式,编辑的内容一定要符合下面的格式:
Example of job definition:
.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr …
| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * user-name command to be executed
输入 crontab -e 进行编辑
五个星* * * * 分别代表分钟、时钟,一个月中的第几天,年,一年中的第几周 , 代表全部
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 二 2022-09-27 12:48:28 CST; 2h 26min ago
Main PID: 701 (crond)
CGroup: /system.slice/crond.service
└─701 /usr/sbin/crond -n
9月 27 12:48:28 localhost.localdomain systemd[1]: Started Command Scheduler.
9月 27 12:48:28 localhost.localdomain crond[701]: (CRON) INFO (RANDOM_DELAY wi…)
9月 27 12:48:29 localhost.localdomain crond[701]: (CRON) INFO (running with in…)
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost bin]# crontab -u root
crontab: usage error: file name must be specified for replace
Usage:
crontab [options] file
crontab [options]
crontab -n [hostname]
Options:
-u define user
-e edit user’s crontab
-l list user’s crontab
-r delete user’s crontab
-i prompt before deleting
-n set host in cluster to run users’ crontabs
-c get host in cluster to run users’ crontabs
-s selinux context
-x enable debugging
Default operation is replace, per 1003.2