Cannot get PHP cron script to run

2019-01-15 21:35发布

I have a PHP script that I need to run every minute. I have made sure that the script works from the command line, and I'm using absolute paths to avoid any environment issues:

/usr/bin/php -q /var/www/myapp/services/myservice.php

Manually running that as root from the command line works fine, as I can see from the log file that my script writes to. To be sure, the script has execute permissions as well.

However, when placing the same exact command in a cron:

* * * * * /usr/bin/php -q /var/www/myapp/services/myservice.php

It does not run or at least it appear so. I've tried redirecting the output to another log file too:

* * * * * /usr/bin/php -q /var/www/myapp/services/myservice.php >> /mylog.log 2>&1

Still nothing. I have no indication whatsoever of the script being ran. I guess it doesn't, but I have no idea what else to look for. I even restarted the cron daemon.

I know there are similar questions on StackOverflow, but none of the answers turned out to be a solution for me. This is literally driving me crazy, I will greatly appreciate any help.

4条回答
Viruses.
2楼-- · 2019-01-15 22:15

This might be considered "bad practice" but it works for me.

Run it with curl

* * * * * curl -s http://www.domain.com/services/myservice.php
查看更多
时光不老,我们不散
3楼-- · 2019-01-15 22:16

I found a solution for my issue:

https://serverfault.com/questions/97828/php-from-command-line-path-problems/97881#97881

It turns out I needed to cd (change directory) into the script dir and then call it. Surprising, since I'm using absolute paths, but it works. Thanks to those who have taken the time to respond.

查看更多
Anthone
4楼-- · 2019-01-15 22:19

There are usually a significant number of things you need to do to move an executable from the command line to a cron job.

By default, cron jobs get a minimal environment which will almost certainly not have the full path (and a host of other environment variables) that your login sessions have. You may also not be in the same directory (as you have discovered).

What I tend to do is to execute:

env | sed 's/^/export /' >$HOME/cron.env

from a login session to get the full environment, then make sure that my cron jobs execute that script before attempting to do the real work. The resultant script may need a small amount of tidying up (quoting, removing transient environment variables like _ and PWD and so forth).

That way I can be sure that the login and cron environments are identical.

查看更多
甜甜的少女心
5楼-- · 2019-01-15 22:30

you missed the running user section:

* * * * * nobody  /usr/bin/php -q /var/www/myapp/services/myservice.php >> /mylog.log 2>&1
查看更多
登录 后发表回答