如何使cron执行php脚本? [英] How can I make a cron to execute a php script?

查看:297
本文介绍了如何使cron执行php脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的服务器每五分钟执行一个php脚本,它是一个单独工作的php脚本,我尝试,因为我的浏览器和从控制台使用php -f php_file.php。但我需要每天自动执行。我在Google上搜索,但是任何解决方案都适用于我:

I want execute a php script each five minutes at my server, it is a php script which works fine alone, I tried since my browser and since console using "php -f php_file.php". But I need execute it automatically every days. I was searching on Google and here to make it but any solution worked for me:

首先我编辑我的crontab,我也重新启动cron,正确。

First I edit my crontab and I also restart the cron to make sure that it was updated correctly.

*/5 * * * * /usr/bin/php /var/www/myscript.php

,我也尝试了下面的例子:

and I tried the following too:

*/5 * * * * /usr/bin/php -f /var/www/myscript.php

我使脚本可执行,查看我的系统日志(我可以看到我的cron正在正确执行,但它不执行php脚本),我也尝试重定向输出cron到文件,但它将文件留空。
任何人都可以帮助我?

I made the script executable too, review my system log (where I can see that my cron is executing correctly, but it doesn't execute php script) and I also try to redirect the output of cron to a file, but it leaves the file empty. Anyone can help me?

最好的祝福

推荐答案

如果需要,请再次执行

$ chmod +x script.php

将此添加到档案:

#!/usr/bin/php
<?php
// here goes your script

您可以通过运行此脚本来测试脚本是否执行

you can test if the script executes by running it like this

$ ./script.php

设置您的 cron 作业,如下所示设置一些日志记录,但确保从脚本输出一些东西,使用 print echo 和相关消息。

set-up your cron job like below to set-up some logging but make sure you output something from your script, use print or echo and a relevant message.

*/5 * * * * /var/www/script.php >> /var/www/script.log 2>&1

我们正在重定向标准输出和错误进入 script.log 文件。

we are redirecting both standard output and errors into the script.log file.

每5分钟检查一次活动。

check every 5 min for activity.

在您的php脚本中尝试此操作

Try this in your php script

$file = '/var/www/script.txt';
for($i=0;$i<9;$i++){
    $entry = date("Y-m-d H:i:s") . " " . $i . PHP_EOL;
    echo $entry; // this should write to the log file

    file_put_contents($file, $entry, FILE_APPEND | LOCK_EX); 
    // and this should write to the script.txt file
}

基本上我们给了文件的完整路径并传递 FILE_APPEND 标志,所以我们不会每次都覆盖。

basically we are giving the full path to the file and passing the FILE_APPEND flag so we don't overwrite every time.

运行脚本并检查文件是否已创建,默认行为是创建文件(如果不存在)。

Run the script and check if the file is created, the default behavior is to create the file if it doesn't exist.

这篇关于如何使cron执行php脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆