定时任务在日常开发中的重要性不用多说了,直接上方法。
下面以ubuntu 18.04系统为例,来看下如何配置定时任务。
- 下载cron
root@ubuntu18-vmware:~# apt-get install cron
- 查看cron命令帮助:
root@ubuntu18-vmware:~# crontab --help
crontab: invalid option -- '-'
crontab: usage error: unrecognized option
usage: crontab [-u user] file
crontab [ -u user ] [ -i ] { -e | -l | -r }
(default operation is replace, per 1003.2)
-e (edit user's crontab)
-l (list user's crontab)
-r (delete user's crontab),若仅要移除一项,请用 -e 去编辑
-i (prompt before deleting user's crontab)
-u :只有 root 才能进行这个任务,亦即帮其他使用者创建/移除 crontab 工作日程。
- 开启定时任务:crontab -e
更改crontab编辑器为vim:
# crontab to vim
export EDITOR=vim
定时任务语句格式为:执行周期 + 命令。
周期有5个域,分别是分钟,小时,日(day of month),月(month of year),周几(day of week)。每个域不加限制任意的话用*。
格式为:
* * * * * user command
分 时 日 月 周 用户 命令
执行脚本:/home/master/a.sh
每分钟运行一次:
*/1 * * * * /home/master/a.sh
- 查询目前的 crontab 内容
crontab -l
*/1 * * * * /home/master/a.sh
- 清空使用者目前的 crontab:
crontab -r
- 查看定时任务的运行情况(执行上述的定时任务):
master@ubuntu18-vmware:~$ cat a.sh
echo "crontab for linux" >> crontab.txt
master@ubuntu18-vmware:~$ cat crontab.txt
crontab for linux
crontab for linux
crontab for linux
可以看到,定时任务每分钟追加写入一行。
- crontab的限制:
/etc/cron.allow:将可以使用 crontab 的帐号写入其中,若不在这个文件内的使用者则不可使用 crontab;
/etc/cron.deny:将不可以使用 crontab 的帐号写入其中,若未记录到这个文件当中的使用者,就可以使用crontab 。
重启cron 服务
systemctl restart cron
检查cron服务的状态
systemctl status cron
- 常用cron表达式:
每五分钟执行 */5 * * * *
每小时执行 0 * * * *
每天执行 0 0 * * *
每周执行 0 0 * * 0
每月执行 0 0 1 * *
每年执行 0 0 1 1 *
- Ubuntu开启crontab运行日志:
Ubuntu服务器/var/log下默认没有cron日志的,要修改rsyslog。
sudo vim /etc/rsyslog.d/50-default.conf
cron.* /var/log/cron.log #将cron前面的注释符去掉
重启rsyslog
systemctl restart rsyslog
注:centos自动开启log,文件为:/var/log/cron。
- 查看crontab日志:
master@ubuntu18-vmware:/var/log$ tail -f cron.log
Dec 7 23:32:01 ubuntu18-vmware CRON[1015]: (master) CMD (/home/master/a.sh)
Dec 7 23:33:01 ubuntu18-vmware CRON[1093]: (master) CMD (/home/master/a.sh)
Dec 7 23:34:01 ubuntu18-vmware CRON[1157]: (master) CMD (/home/master/a.sh)