2. 编辑crontab文件
crontab位于/ect/文件夹。
打开crontab文件,如果没有编辑过可以看到如下类似的内容:
# /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
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
由于对脚本的认知有限,不能详细解释每个命令的含义。在第10行,同样定义了文件内容的格式。可以看到比使用crontab -e命令时,多了一个user。它表示了执行命令的用户,如果是root,就表明是系统用户。于是,我加了如下一行:
3 * * * * root /home/meng/hello.sh
然后保存文件。
这时需要的注意是,要重新启动系统,修改才能起作用。(只重启cron守护进程可以吗?)如果以前使用crontab -e进行了修改,建议先注释掉,不然就不知道是哪个方法在起作用了。
当然,结果也在意料之中,脚本定时顺利执行。
虽然解决了问题,但是还有一个疑问:
在一篇文章中看到,run-parts参数是表示执行文件夹下的所有文件,也就是说,上面的内容可以写成:
3 * * * * root run-parts /home/meng
不过,我在测试中好像并没有达到预想结果,也许是我测试步骤出了问题。这里做个记号。
