What are the best practices for scheduling tasks in PHP, such as copying and deleting database entries after a certain time has passed?

When scheduling tasks in PHP, such as copying and deleting database entries after a certain time has passed, it is best to use a cron job to run a PHP script at specified intervals. Within the PHP script, you can query the database for entries that meet the criteria for copying or deleting based on the elapsed time. It is important to handle error checking and logging within the script to ensure the tasks are executed correctly.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query the database for entries older than a certain time
$sql = "SELECT * FROM table WHERE timestamp < DATE_SUB(NOW(), INTERVAL 1 HOUR)";
$result = $conn->query($sql);

// Copy or delete entries based on the query results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Copy or delete entry logic here
    }
} else {
    echo "No entries to copy or delete";
}

// Close the database connection
$conn->close();
?>