For linux users (Ubuntu 18.04, tested version)
Let’s go to a practical and real example:
1st Step) Let’s create a table named logs in your database.
CREATE TABLE `logs` (
`id` int(11) NOT NULL,
`description` mediumtext NOT NULL,
`date` datetime NOT NULL,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2) Let’s create the algorithm in a PHP file that makes the insertion.
In the xamp or wamp folder or in the folder your html codes are in, create a folder named cron, within it create a file called test.php, within that file (test.php), insert this code:
<?php
$servername = "localhost";
$username = "root";
$password = "minhasenha_aqui";
$dbname ="meubancodedados_aqui";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO logs (description, date)VALUES ('Demo CRON','2021-09-01 19:09:00')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
3rd Step)
For example, we use the software utility: curl
.
install it using this command: sudo apt install curl
.
Step 4) Let’s manipulate the cron software utility.
First, see if it is installed, use this command: crontab -e
, will normally ask you to edit the cron file.
Type this command:
* * * * * Curl http://localhost/cron/test.php
Press Ctrl+x and save the file.
Ready! Now, every minute, every hour, every day, every week and every month, the http://localhost/cron/test.php file will be executed by entering the information we did in step 2.
If the data to be entered does not depend on PHP, you can use the Mysql Event Scheduler: http://dev.mysql.com/doc/refman/5.7/en/events-overview.html
– Daniel Omine