使用 www-data 用户运行定时任务(cron)

其实这个没啥好说的,就是记录下解决的过程(说得好像跟一篇水文似的…)。或者给遇到这类问题的小伙伴提供个思路。

痛点

我们在部署 web 服务时,经常用到定时任务。正常的流程就是直接执行下面的指令来配置定时任务

1
crontab -e

问题来了,正常情况下,这个指令在哪个用户下面执行,这个权限就是谁的(如果你听不懂我在说啥,那基本就是属于 root的)。

定时任务本身的配置也是个精细活,你可以阅读下 https://learnku.com/articles/25177 看看你之前用的姿势是不是还能优化。

常见问题之日志权限

这怕是最常见的问题了。定时任务出错了,记录日志到 storage/logs 里了,一般就是 laravel.log 文件。

此时 laravel.log 所属者就是 root 了。

用户通过浏览器访问我们网站,如果出错,以 www-data 身份尝试记录到 storage/logs/laravel.log,然后写不进去,一直报错,真香!

解决

打开谷歌搜索 run cron job as www-data。找到了文章 https://askubuntu.com/questions/189189/how-to-run-crontab-as-userwww-data

谷歌真香!

具体的意思,就是直接在 /etc/crontab 中编辑定时任务即可,加上用户名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# /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
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 )
#


# cron
* * * * * www-data flock /tmp/flock1.lock -c 'timeout 200 /usr/local/bin/php /var/www/html/laravel/artisan command >> /home/log/laravel.log 2>&1'

啰嗦下:

  • flock 用来防止重复执行,起到原子锁作用
  • timeout 表示这个脚本执行过长,咱就干死它,可以有效避免各种循环或长时间占用问题
  • >> 表示向文件中追加内容
  • 2>&1 表示将标准错误输出重定向到正确输出(这样你万一有程序出错,也能记录下)

真香后传(更新于 2019年11月06日19:38:27)

如果你按照上述的进行,你会发现还是执行不了定时任务。因为 www-data 默认是不能执行 bash 相关操作的。

使用真香的谷歌搜索 www-data run cron error,我们发现了宝藏 https://ubuntuforums.org/showthread.php?t=2334330

The www-data user is not able to invoke a shell by default. In /etc/passwd you’ll see
Code:
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
If you want to be able to run scripts as that user, you’ll need to change “/usr/sbin/nologin” to “/bin/bash”.

好了,咱们把 /etc/passwd 里面 www-data 对应的那一行改下就可以了。

另外

其实你还可以用 crontab -u www-data CRON_FILE 来指定用户运行指定的定时任务。