


Sharing examples of using the sleep function to implement scheduled tasks in PHP, phpsleep_PHP tutorial
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
/**
* 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
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:
/**
* 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
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:
/**
* 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:
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:
/**
* 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
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
php
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.
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
