vi /etc/crontab
修改内容如下(设置test.sh每分钟执行一次,输出到test.log文件):
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# 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
* * * * * root /home/script/test.sh >> /home/script/log/test.log 2>&1
观察日志和错误解决
错误1
等待一段时间,发现没有test.log输出,观察日志 tail -f /var/log/cron.log,发现如下错误:
ubuntu error: bad minute; while reading /etc/crontab
尝试:重新安装启动cron,仍然相同的错误。
解决方案:尝试 cat -v /etc/crontab,查看不可见字符发现文档如下:
# /etc/crontab: system-wide crontab^M
# ……
* * * * * root /home/script/test.sh >> /home/script/log/test.log 2>&1^M
意识到这是因为我在windows idea上创建的文件,文件格式错误,改成 unix格式就可以解决这个问题。
错误2
修改文件后再次运行,观察日志 tail -f /var/log/cron.log,发现如下错误
the crontab file should end with an empty line
解决办法:在文件末尾加个换行符。
错误3
定时任务执行了,日志未输出 → 创建日志文件夹。
执行和观察测试
- tail -f /var/log/cron.log 每分钟都有定时任务执行记录
- tail -f /home/srcipt/test.log 每分钟都有test.sh的输出
- 断电重启计算机,定时任务仍然会启动