What are the best practices for ensuring that PHP scripts for database updates do not exceed the max_execution_time limit?

When running PHP scripts for database updates, it's important to ensure that they do not exceed the max_execution_time limit set in the PHP configuration. One way to prevent this is by breaking up large database update tasks into smaller chunks and periodically checking the execution time to avoid hitting the limit.

// Set the maximum execution time for the script
ini_set('max_execution_time', 300); // 5 minutes

// Perform database updates in smaller chunks
$recordsPerPage = 100;
$totalRecords = getTotalRecords(); // Function to get total number of records

for ($offset = 0; $offset < $totalRecords; $offset += $recordsPerPage) {
    $records = getRecords($offset, $recordsPerPage); // Function to retrieve records in chunks
    foreach ($records as $record) {
        // Update database record
        updateRecord($record);
    }
    
    // Check execution time and exit loop if approaching limit
    if (time() - $_SERVER['REQUEST_TIME'] >= ini_get('max_execution_time') - 10) {
        break;
    }
}