Case and Solution of mysql Read Failure Caused by sleep in PHP

  • 2021-07-13 04:46:35
  • OfStack

Recently, due to project requirements,
Need to use the sleep function to take 1 heap of data from the database regularly to perform some operations.
sleep waits for at least 1 hour
I have been tested before
It is feasible to use sleep function to complete the operation performed after several hours

But the problem of the evil door came out
After using sleep, the program found that it could not get the corresponding information from the database
Remove sleep
The result is normal

Depressed. . .
Does sleep affect the library reading operation! ! !
So for the convenience of testing,
Go straight to sleep (10) and execute it in 10 seconds
As a result, information can be read from the database

But why can't sleep () read the information after 1 hour?
For the convenience of testing, I read the library once directly before sleep statement and once again after sleep statement
Such as:


<?php
require_once('include.php');
// Read database information
$data = $db->getList();
print_r($data);
 
// Timing 1 Hours later
sleep(3600);
 
// Re-read 1 Secondary information
$data = $db->getList();
print_r($data);
 
?>

It turns out that
The first library read was successful
The second read library is empty

Then change the sleep to 10 seconds and then test it again

<?php
require_once('include.php');
// Read database information
$data = $db->getList();
print_r($data);
 
// Timing 10 Seconds later
sleep(10);
 
// Re-read 1 Secondary information
$data = $db->getList();
print_r($data);
 
?>

Above results
Read the library successfully twice

Why did you fail to read the library in 1 hour but succeed in 10 seconds? ?
I use a singleton database operation class
Think of a question
Could it be that the database connection timeout caused the database reading failure?
So I quickly changed the library reading operation here to the current connection

<?php
require_once('include.php');
// Read database information
$data = getList();
print_r($data);
 
// Timing 1 Hours later
sleep(3600);
 
// Re-read 1 Secondary information
$data = getList();
print_r($data);
 
// Read database information
function getList(){
        $pdo = new PDO('mysql:host=localhost;dbname=test','root','root');
        $result = $pdo->query('select * from tables');
        return $result->fetchAll(PDO::FETCH_ASSOC);
}
?>

The test was successful! !
The original sleep will lead to singleton class timeout problem, so that the database connection may be disconnected after the execution time is too long, and the database information cannot be read!


Related articles: