PHP Timer implementation runs every few seconds

Source: Internet
Author: User


Let's write a simple example to illustrate this approach.

<?php
Ignore_user_abort ()//close browser still executes
Set_time_limit (0)//Let the program continue to execute
$interval =3;//run at certain times
do{
$msg =date ("y-m-d h:i:s");
File_put_contents ("Log.log", $msg, file_append);//Logging
Sleep ($interval);//wait time for the next action.
}while (TRUE);
?>

What needs to be explained is: The program does not write the end Judgment statement, he will infinite loop down. Of course, if you want to stop, you can restart Apache, restart after the invalid. To perform the timed execution again, run the code again.

The above simple example can illustrate this principle.
So for the above example, I can carry on the improvement plan.

You need a switch that executes the script, and you can do it using 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 the PHP code
Set_time_limit (0);//Program Execution Time Unlimited
$sleep _time = 5;//how long to execute
$switch = include ' switch.php ';
while ($switch) {
$switch = include ' switch.php ';
$msg =date ("y-m-d h:i:s"). $switch;
File_put_contents ("Log.log", $msg, file_append);//Logging
Sleep ($sleep _time);//wait time to do the next action.
}
Exit ();

?>


Of course, we can also use the timing of the system to execute PHP script, the following look at a linux example.

Using PHP to execute scripts in crontab

Just like calling a normal shell script in crontab (specifically crontab usage), use a PHP program to invoke the PHP script.
The following myscript.php are performed every hour:

# CRONTAB-E
* * * * * */usr/local/bin/php/home/john/myscript.php

/usr/local/bin/php is the path to the PHP program.

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.