os: ubuntu 16.04
linux crontab 在实际工作中大量使用,这里简单记录下。
cron服务
cron 在安装os都是默认安装的,如果发现没有安装,可以 apt 安装,对于 redhat 分支可以使用 yum 安装。
# ps -ef|grep cron
root 929 1 0 10:15 ? 00:00:00 /usr/sbin/cron -f
# /etc/init.d/cron
* Usage: /etc/init.d/cron {start|stop|status|restart|reload|force-reload}
# systemctl status cron.service
# systemctl stop cron.service
# systemctl start cron.service
# systemctl disable cron.service
# systemctl enable cron.service
# cat /lib/systemd/system/cron.service
[Unit]
Description=Regular background program processing daemon
Documentation=man:cron(8)
[Service]
EnvironmentFile=-/etc/default/cron
ExecStart=/usr/sbin/cron -f $EXTRA_OPTS
IgnoreSIGPIPE=false
KillMode=process
[Install]
WantedBy=multi-user.target
常见的一些配置
*(星号)
代表任何时刻都接受的意思。举例来说,0 12 * * * command 日、月、周都是*,就代表着不论何月、何日的礼拜几的12:00都执行后续命令的意思。
,(逗号)
代表分隔时段的意思。举例来说,如果要执行的工作是3:00与6:00时,就会是:0 3,6 * * * command时间还是有五列,不过第二列是 3,6 ,代表3与6都适用
-(减号)
代表一段时间范围内,举例来说,8点到12点之间的每小时的20分都进行一项工作:20 8-12 * * * command仔细看到第二列变成8-12.代表 8,9,10,11,12 都适用的意思
/n(斜线)
那个n代表数字,即是每隔n单位间隔的意思,例如每五分钟进行一次,则:/5 * * * * command用与/5来搭配,也可以写成0-59/5,意思相同
1 crobtab 的格式如下:
# 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
简单记忆为:分时日月周脚本
2 crontab 查看
# crontab -l
# crontab -l > /tmp/mycron
3 crontab 编辑
$ crontab -e
4 crontab 示例
0 * * * * /bin/echo `date` > /tmp/da
0,15,30,45 * * * * /bin/echo `date` > /tmp/da
0,15,30,45 18-06 * * * /bin/echo `date` > /tmp/da
0,15,30,45 18-06 */2 * * /bin/echo `date` > /tmp/da
0,15,30,45 18-06 */2 * 6 /bin/echo `date` > /tmp/da
00 18 * * * script -c "/apps/log_done.sh >> /apps/log_done.log"
00 18 * * * /apps/log_done.sh >> /apps/log_done.log 2>&1
00 18 * * * /apps/log_done.sh >> /apps/log_done.log 2>&1 &