问题
I need to run a PHP file every 1 hour.
What I'm doing is:
sudo crontab -e
(In the editor) * 01 * * * /usr/bin/php /var/www/devicecheck.php
But somehow, it's not working. The command works on the command line. Before this, I was trying php /var/www/devicecheck.php
Any suggestions?
回答1:
To execute devicecheck.php every 1 hour try the following:
Method A :: Execute the script using php from the crontab
# crontab -e
00 * * * * /usr/bin/php/var/www/devicecheck.php
Method B: Run the php script using URL from the crontab
If your php script can be invoked using an URL, you can lynx, or curl, or wget to setup your crontab as shown below.
The following script executes the php script (every hour) by calling the URL using the lynx text browser. Lynx text browser by default opens a URL in the interactive mode. However, as shown below, the -dump option in lynx command, dumps the output of the URL to the standard output.
00 * * * * lynx -dump http://www.yourwebsite.com/yourscript.php
The following script executes the php script (every 5 minutes) by calling the URL using CURL. Curl by default displays the output in the standard output. Using the “curl -o” option, you can also dump the output of your script to a temporary file as shown below.
*/5 * * * * /usr/bin/curl -o temp.txt http://www.yourwebsite.com/yourscript.php
The following script executes the php script (every 10 minutes) by calling the URL using WGET. The -q option indicates quite mode. The “-O temp.txt” indicates that the output will be send to the temporary file.
*/10 * * * * /usr/bin/wget -q -O temp.txt http://www.yourwebsite.com/yourscript.php
UPDATE::
# chmod a+x /home/username/yourscript.php
# crontab -e
00 * * * * /home/username/yourscript.php
回答2:
Script should have execute permission. Give it by
chmod +x /var/www/devicecheck.php
Also check /var/log/syslog
for Errors.
回答3:
I got it to work with wget. You maybe have to install wget first. After it will allow you to run php scripts from a cronjob. The syntax looks like:
* 01 * * */usr/local/bin/wget "http://localhost/devicecheck.php"
Where /usr/local/bin/wget points to the directory where wget is installed. If you wish no output just add '-O /dev/null', like this:
* 01 * * */usr/local/bin/wget "http://localhost/devicecheck.php" -O /dev/null
You can also pass parameters in the url:
* 01 * * */usr/local/bin/wget "http://localhost/devicecheck.php?task=somevalue" -O /dev/null
来源:https://stackoverflow.com/questions/35553370/running-php-file-using-crontab