Heim  >  Artikel  >  php教程  >  定时执行php文件例子(php计划任务)

定时执行php文件例子(php计划任务)

WBOY
WBOYOriginal
2016-05-25 16:40:351063Durchsuche

本文章给各位整理了三种php计划任务的例子,分别是利用了windows,linux及php的ignore_user_abort的函数来执行,下面我给大家分别举几个例子,有兴趣的朋友可进入参考.

WINDOWS中设置计划任务执行PHP文件

1、写一个PHP程序,命名为test.php,内容如下所示,代码如下:

<?php 
    $fp = fopen("test.txt", "a+"); 
    fwrite($fp, date("Y-m-d H:i:s") . " 成功成功了!n"); 
    fclose($fp); 
?>

程序大胆地写,什么include/require尽管用,都没问题.

2、新建Bat文件,命名为test.bat,内容如下所示:

D:phpphp.exe -q D:websitetest.php

3、建立WINDOWS计划任务:

开始–>控制面板–>任务计划–>添加任务计划

浏览文件夹选择上面的bat文件

设置时间和密码(登陆WINDOWS的)

保存即可了.

4、大功告成,可以右键计划任务点"运行"试试

用PHP脚本实现定时任务:

PHP脚本执行时间限制,默认的是30m 解决办法:set_time_limit();或者修改PHP.ini 设置max_execution_time时间(不推荐).

如果客户端浏览器关闭,程序可能就被迫终止,解决办法:ignore_user_abort即使关闭页面依然正常执行.

如果程序一直执行很有可能会消耗大量的资源,解决办法使用sleep使用程序休眠一会,然后在执行.

PHP定时执行的代码如下:

<?php 
    ignore_user_abort();//关掉浏览器,PHP脚本也可以继续执行. 
    set_time_limit(3000);// 通过set_time_limit(0)可以让程序无限制的执行下去 
    $interval=5;// 每隔5s运行 
    //开源代码phprm.com 
    //方法1--死循环 
    do{ 
        echo &#39;测试&#39;.time().&#39;<br/>&#39;;  
        sleep($interval);// 等待5s 
    }while(true); 
     
    //方法2---sleep 定时执行 
    require_once &#39;./curlClass.php&#39;;//引入文件 
     
    $curl = new httpCurl();//实例化 
    $stime = $curl->getmicrotime(); 
    for($i=0;$i<=10;$i++){ 
     
    echo &#39;测试&#39;.time().&#39;<br/>&#39;;  
    sleep($interval);// 等待5s 
     
    } 
    ob_flush(); 
    flush(); 
    $etime = $curl->getmicrotime(); 
    echo &#39;<hr>&#39;; 
    echo round(($etime-stime),4);//程序执行时间 
?>

Linux的Crontab执行PHP脚本

一、在Crontab中使用PHP执行脚本

就像在Crontab中调用普通的shell脚本一样(具体Crontab用法),使用PHP程序来调用PHP脚本.

每一小时执行myscript.php如下:

# crontab -e
00 * * * * /usr/local/bin/php /home/john/myscript.php

/usr/local/bin/php为PHP程序的路径。

二、在Crontab中使用URL执行脚本

如果你的PHP脚本可以通过URL触发,你可以使用lynx或curl或wget来配置你的Crontab.

下面的例子是使用Lynx文本浏览器访问URL来每小时执行PHP脚本,Lynx文本浏览器默认使用对话方式打开URL,但是,像下面的,我们在lynx命令行中使用-dump选项来把URL的输出转换来标准输出,代码如下:

00 * * * * lynx -dump /myscript.php

下面的例子是使用CURL访问URL来每5分执行PHP脚本,Curl默认在标准输出显示输出,使用"curl -o"选项,你也可以把脚本的输出转储到临时文件,代码如下:

*/5 * * * * /usr/bin/curl -o temp.txt /myscript.php

下面的例子是使用WGET访问URL来每10分执行PHP脚本,-q选项表示安静模式,"-O temp.txt"表示输出会发送到临时文件,代码如下:

 */10 * * * * /usr/bin/wget -q -O temp.txt /myscript.php


本文地址:

转载随意,但请附上文章地址:-)

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn