Detailed PHP implementation of timed tasks _php skills

Source: Internet
Author: User
Tags php script

PHP in this respect should be said to be relatively weak, if only the implementation of PHP can be as follows:

<?php
 Ignore_user_abort ()//After closing the browser, continue to execute PHP code
 set_time_limit (0);/program Execution Time Unlimited
 $sleep _time = 1;// How often
 to perform a do{
 $fp = fopen (' test.txt ', ' A + ')
 ; Fwrite ($FP, "This is a PHP blog: phpddt.com \ n");
 Fclose ($FP);
 Sleep ($sleep _time);
 } while (true);
 
? >

But when I execute the script, even if I shut down the browser, I can't stop the program at all, so you need a switch that executes the script, and you can do it with the method introduced by the external file, in the while loop, include the switch variable. Then you can do this:
Create an externally introduced variable file switch.php content as follows:

<?php return
1;//1 Execute script 0 exit Execute script
?>

The improved script is as follows:

<?php
 Ignore_user_abort ()//After closing the browser, continue to execute PHP code
 set_time_limit (0);/program Execution Time Unlimited
 $sleep _time = 5;// How often do
 $switch = include ' switch.php ';
 while ($switch) {
 $switch = include ' switch.php ';
 $fp = fopen (' test.txt ', ' A + ');
 Fwrite ($FP, "This is a PHP blog: phpddt.com $switch \ n");
 Fclose ($FP);
 Sleep ($sleep _time);
 }
 Exit ();
 
? >

This script is just a test of the feasibility, the specific efficiency should not be high, for lamp, you can use crontab to achieve.
Add a little bit of code:

Ignore_user_abort ()//Turn off the browser, the PHP script can also continue to execute.
Set_time_limit (0);//Through Set_time_limit (0) allows the program to execute indefinitely
$interval =60*30;//run every half hour
do{
  //This is the code you want to execute. Sleep  
  ($interval);//wait 5 minutes
} while (true);

About the implementation of PHP scheduled tasks for everyone to introduce so much, and then have related articles for everyone to share, do not miss.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.