Home > Backend Development > PHP Tutorial > Sharing examples of using the sleep function to implement scheduled tasks in PHP, phpsleep_PHP tutorial

Sharing examples of using the sleep function to implement scheduled tasks in PHP, phpsleep_PHP tutorial

WBOY
Release: 2016-07-13 10:20:23
Original
1014 people have browsed it

Use the sleep function in PHP to share scheduled task instances, phpsleep

In some programs, there are some special functions that require scheduled execution. Friends who are familiar with Linux will definitely say that this is not easy. Is it possible to create a scheduled task crontab soon? This is indeed achievable, but the specific execution time must be known in advance before it can be written into the planned task. For example, two o'clock in the morning, seven o'clock in the morning, or six thirty in the morning every day, etc.

However, sometimes, we cannot predict this time, and the execution time is dynamically generated by the program. Then execute certain program fragments after the dynamically generated time. You cannot use Linux's crontab to schedule tasks here, because the time of each execution is dynamically generated, and the scheduled task needs to know a fixed time. Since scheduled tasks cannot be used, one can only find implementation methods from the program itself.

In PHP, there is a sleep function, which roughly means that when the program execution encounters the sleep function, it pauses for N seconds and then continues execution. For example, sleep(10) means that the program is executed from top to bottom. After encountering the sleep(10) statement, it pauses for ten seconds and then continues execution. The parameter in the function brackets is a numerical value, representing the pause time value, in seconds. Please look at the code below

Copy code The code is as follows:

/**
* Usage of sleep function
* Qiongtai Blog
​*/
// Output the current program timestamp
echo time(); // out:1338088780
echo '
';

// Pause for ten seconds
sleep(10);

// Output timestamp
echo time(); // out:1338088790

The execution result of the above program is
Copy code The code is as follows:

1338088780
1338088790

Let's analyze the execution process. The first step is to print the current timestamp 1338088780, then pause for ten seconds, and then print the timestamp. Since the program waits ten seconds and then prints the timestamp again, the last timestamp must be ten seconds longer than the first timestamp printed. As a result, the last timestamp is 1338088790.

In the above example, we only used the sleep function once, and the sleep() function can be used unlimitedly on the page. Please see the following code:

Copy code The code is as follows:

/**
* Usage of sleep function
* Qiongtai Blog
​*/
// Output the first timestamp
echo time(); // out: 1338088780
echo '
';

// Pause for ten seconds
sleep(10);

// Output the second timestamp
echo time(); // out: 1338088790
echo '
';

// Pause for twenty seconds
sleep(20);

// Output the third timestamp
echo time(); // out: 1338088810

The execution result of the above program is
Copy code The code is as follows:
1338088780
1338088790
1338088810

The above code execution process:
First, print the first timestamp 1338088780
Second, pause for ten seconds
Third, print the second timestamp 1338088790, which is the sum of the first timestamp plus ten seconds
Fourth, pause for twenty seconds
Fifth, print the third timestamp 1338088810, which is the sum of the second timestamp 1338088790 plus twenty seconds.

Sleep appears twice on the page, the first time is ten seconds, and the second time is twenty seconds. It follows that the above example takes a total of thirty seconds to execute. When the sleep() function appears multiple times in the page, it is accumulated instead of overwriting the previous code.

So how do you combine sleep timing to execute code that dynamically generates time? Please look at the following code:

Copy code The code is as follows:

/**
* The sleep function regularly executes the code for dynamically generating time periods
* Qiongtai Blog
​*/
// Current time
echo date('Y-m-d H:i:s'); // out:2012-05-27 14:58:00
echo '
';

// Dynamic generation time ranges from 6pm to 0pm today
$datetime = date('Y-m-d').' '.rand('18,23').':'.rand('0,59').':'.rand('0,59'); // 2012-05-27 19:20:00

// Calculate timestamp
$a = strtotime($datetime);

// Calculate the time difference
$reduce = $a-time();

// sleep wait
sleep($reduce);

// Code block to be executed after the execution time
echo date('Y-m-d H:i:s'); // out:2012-05-27 19:20:00

The above code output:
Copy code The code is as follows:
2012-05-27 14:58:00
2012-05-27 19:20:00

Analysis: Start printing the current time, and then randomly calculate the program execution time 2012-05-27 19:20:00. Since sleep accepts a parameter that is a value in seconds, the generated time is first converted into a timestamp. Then subtract the current timestamp from the timestamp to get a time difference, and then sleep to achieve the scheduled execution effect of the program executing certain statements at a randomly generated time. Note here that a time difference in seconds must be calculated. If the second difference cannot be calculated, the sleep function cannot be used.

Finally, some children may say that my program execution error occurs when doing examples, prompting a timeout. Don’t panic if this problem occurs. This is caused by PHP’s default page execution time. The default page execution time in PHP is thirty seconds, which is enough for general programs. But if you want to do a similar scheduled execution function, you must set the execution time set_time_limit(0) in the header statement. 0 means no time limit, the unit is seconds. Finally, post the code as a whole:

Copy code The code is as follows:

/**
* The sleep function regularly executes the code for dynamically generating time periods
* Qiongtai Blog
​*/
//Set the page execution time, otherwise there will be a timeout error
set_time_limit(0);

// Current time
echo date('Y-m-d H:i:s'); // out:2012-05-27 14:58:00

// Dynamic generation time ranges from 6pm to 0pm today
$datetime = date('Y-m-d').' '.rand('18,23').':'.rand('0,59').':'.rand('0,59'); // 2012-05-27 19:20:00

// Calculate timestamp
$a = strtotime($datetime);

// Calculate the time difference
$reduce = $a-time();

// sleep wait
sleep($reduce);

//The code block to be executed after the execution time is up
echo date('Y-m-d H:i:s'); // out:2012-05-27 19:20:00


How to implement scheduled execution of scripts in PHP?

If you want to use PHP files, you can barely do it
There is a sleep function in php. The specific use is sleep(time) where time is in seconds
First, create a php script
while(1){
//yourcode
sleep(3600*24);
}
?>
The yourcode here is the function you want the PHP script to execute. Although this goal can be achieved, there are sacrifices. You have to access this script through the URL at 8 o'clock in the morning, which means executing the PHP file, and this link cannot be interrupted and must continue! ! Otherwise, it will be invalid

PHP is executed only upon request, and is executed only when there is a request.

Problem with sleep() function in PHP

You need to add an echo str_pad(" ",256);
before the first echo date("h:s:i")."\n"; because IE needs to add 256 The page will not be displayed until after bytes, but it was found that the latest version of Firefox needs to receive 1024 bytes before it can be displayed

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/867248.htmlTechArticleUse the sleep function in PHP to share scheduled task instances. phpsleep In some programs, there are some special functions required Timing execution is used. Friends who are familiar with Linux will definitely say that this is not...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template