PHP实现windows下的定时运行(类似linux的crontab)

发表时间:2010-09-06 文章分类:PHP 阅读:541200

文章链接:http://www.webzone8.com/article/74.html
  直接贴代码了:

<?php
ignore_user_abort(true);           // 即使Client断开(如关掉浏览器),PHP脚本也可以继续执行.
set_time_limit(0);             // 执行时间为无限制,php默认的执行时间是30秒,通过set_time_limit(0)可以让程序无限制的执行下去
$interval = 300;               // 时间间隔 单位 秒
$key_file="key.txt";          // 配置文件

if ( isset($_GET['s']) ) {
  if ( $_GET['s'] == "0" ){        // 停止工作,但不退出
    $s="false";
    echo "关闭";
  } elseif ( $_GET['s'] == "1" ) {      // 工作
    $s="true";
    echo "开启";
  } elseif ( $_GET['s'] == "2" ) {      // 退出
    $s="die";
    echo "退出";
  } else {
    die("Err 0:stop working 1:working 2:exit");
  }
 
  $string = "<?php\n return \"".$s."\";\n?>";
  write_inc($key_file,$string,true);
}

if ( file_exists( $key_file ) ) {
  do{
    $mkey = include $key_file;
    if ( $mkey == "true" ) {          // 如果工作
    /////////////////////  工作区间  //////////////////////////////////
  $filename = "index.php";
  $contents = file_get_contents("http://www.bestlovesky.com/" . $filename);
  $f = fopen("index.html","w");
  fwrite($f,$contents);
  fclose($f);
    ///////////////////////////////////////////////////////////////////
    } elseif ( $mkey=="die" ) {        // 如果退出
      die("退出!");
    }
    sleep($interval);           // 等待$interval秒
  } while ( true ) ;
} else {
  die( $key_file . " 不存在 !" );
}

function write_inc( $path , $strings , $type = false )
{  
  $path = dirname(__FILE__) . "/" . $path;
  if ( $type == false ) {
    file_put_contents( $path , $strings , FILE_APPEND );
  } else {
    file_put_contents( $path , $strings );
  }
}

?>
 


担心有的同学个别地方不明白,做下解释:

ignore_user_abort() 函数设置与客户机断开是否会终止脚本的执行。如果设置为 true,则忽略与用户的断开,如果设置为 false,会导致脚本停止运行,如果未设置该参数,会返回当前的设置。

所以本程序设置了true,通过url访问以下:例如:http://www.bestlovesky.com/sky.php?s=1

然后关掉就行了。

程序就会根据设置的$interval 定时运行了

有趣的视频娱乐一下

原文链接:http://www.webzone8.com/article/74.html

用户评论

用户【37.233.27.*****】说:dZDETz I truly appreciate this article post.Really thank you! Really Great.

用户【27.150.243*****】说:This is the precise blog for anybody who desires to find out about this topic. You notice so much its nearly arduous to argue with you (not that I truly would need匟aHa). You definitely put a brand new spin on a topic thats been written about for years. Nice stuff, simply great!

用户【27.150.243*****】说:I must point out my love for your kindness for men and women who must have assistance with in this concern. Your personal dedication to getting the solution all through came to be rather functional and has in most cases helped women like me to attain their dreams. Your entire valuable useful information signifies so much to me and even further to my fellow workers. Thank you; from each one of us.

用户【27.150.243*****】说:I抎 have to test with you here. Which is not something I usually do! I get pleasure from reading a put up that may make folks think. Also, thanks for permitting me to remark!

用户【27.150.243*****】说:I enjoy you because of your entire labor on this web site. Betty really loves engaging in investigation and it is simple to grasp why. We all notice all of the powerful medium you give simple ideas via your website and therefore invigorate contribution from visitors about this subject matter so our girl has always been being taught a great deal. Have fun with the remaining portion of the new year. You are doing a fabulous job.

用户【155.254.96*****】说:Thank you so much with regard to giving me personally an update on this subject matter on your site. Please know that if a brand-new post becomes available or if any alterations occur on the current posting, I would want to consider reading a lot more and understanding how to make good using of those techniques you write about.Thanks for your time and consideration of other men and women by making this site available.

用户【31.184.236*****】说:&lt;a href=&quot;http://torontoadrugstore.ru/&quot;&gt;canadian pharmacy no prescription&lt;/a&gt; &lt;a href=&quot;http://onlinepharmaciesacanada.ru/&quot;&gt;canadian pharmacy&lt;/a&gt; &lt;a href=&quot;http://onlinepharmacyawithoutaprescription.ru/&quot;&gt;mexican pharmacy no prescription needed&lt;/a&gt; &lt;a href=&quot;http://canadianonlineapharmacy.ru/&quot;&gt;Canadian Online Pharmacy&lt;/a&gt; &lt;a href=&quot;http://freecialisasamples.ru/&quot;&gt;viagra and cialis sample pack&lt;/a&gt; &lt;a href=&quot;http://viagrawithoutaprescriptions.ru/&quot;&gt;viagra prescription price&lt;/a&gt; &lt;a href=&quot;http://onlinepharmaciesa.ru/&quot;&gt;online pharmacies canada&lt;/a&gt; &lt;a href=&quot;http://bestprice100mgaviagra.ru/&quot;&gt;best india viagra and price&lt;/a&gt; &lt;a href=&quot;http://cialisa40mg.ru/&quot;&gt;cialis_original_10mg&lt;/a&gt; &lt;a href=&quot;http://viagraasamples.ru/&quot;&gt;free viagra samples before buying&lt;/a&gt;

用户【27.150.243*****】说:Can I simply say what a reduction to seek out someone who truly knows what theyre speaking about on the internet. You positively know find out how to bring a difficulty to mild and make it important. Extra folks need to read this and understand this side of the story. I cant imagine youre no more common because you definitely have the gift.

用户【93.188.37.*****】说:На нашем портале мы предлагаем огромный выбор роз. Варианты букетов роз вы сможете посмотреть и заказать подходящие для вас розы в нашем каталоге. [url=https://roses.kh.ua/bukety/svadebnye-bukety]букет невесты 2017[/url]. На портале вы можете приобрести недорогие цветы в Харькове с доставкой. Также с помощью нашего ресурса вы имеете послать букет роз по Интернету с помощью курьерской экспресс доставки. Мы продаём классические и дизайнерские букеты роз различных оттенков и видов, букеты для свадеб, а ещё подарки и различные сладости. У нас трудятся абсолютно опытные флористы, которые красиво оформят каждый заказ для доставки роз по Харькову и другим крупным городам области. [url=https://roses.kh.ua/uk/buketi]букет квітів троянди купити[/url]. У нас очень дешёвые и красивые розы в Харькове! Наши розы с доставкой по Харькову пользуются огромным спросом. Наши квалифицированные и профессиональные курьеры смогут в кратчайшее время доставить приобретённые розы в Харькове или по области независимо от места расположения адресата и времени суток. [url=https://roses.kh.ua/uk/buketi]троянди букет замовлення[/url]. Приобрести букет роз или несколько букетов с доставкой по городу и области вы можете как по телефонам, указанным на нашем сайте, так и оставив заявку на приобретение с доставкой. Наши сотрудники уточнят все подробности по заказу и отправят его по нужному адресату в очень сжатый срок.

用户【5.188.211.*****】说:OxKBhh http://www.FyLitCl7Pf7ojQdDUOLQOuaxTXbj5iNG.com

用户【27.150.243*****】说:It抯 arduous to search out educated folks on this subject, but you sound like you understand what you抮e speaking about! Thanks

用户【27.150.243*****】说:I not to mention my pals appeared to be looking at the nice recommendations from your web site and all of the sudden got a horrible suspicion I never expressed respect to the blog owner for those tips. These young men were as a consequence happy to read through them and have now undoubtedly been enjoying them. Many thanks for truly being very accommodating and for considering varieties of decent information most people are really desirous to be aware of. My very own sincere regret for not expressing appreciation to sooner.

用户【27.150.243*****】说:That is the precise blog for anyone who wants to find out about this topic. You understand so much its virtually onerous to argue with you (not that I truly would want匟aHa). You undoubtedly put a new spin on a subject thats been written about for years. Great stuff, simply great!

用户【115.60.56.*****】说:bulk wholesale standard size cotton tote bag http://www.angtebags.com/bulk-wholesale-standard-size-cotton-tote-bag/ bulk wholesale standard size cotton tote bag

用户【115.60.56.*****】说:Oem Production Diy Messenger Canvas Beach Bag For Girls http://www.angtebags.com/oem-production-diy-messenger-canvas-beach-bag-for-girls/ Oem Production Diy Messenger Canvas Beach Bag For Girls

12345678910...319下一页

发表评论

姓名:*
邮箱:*
网站:*