Run PHP function to insert data into DB daily at specific times

Asked

Viewed 1,125 times

3

I am creating a "module" of my system and now I have to create a function that, when arriving at the time that is in the database, run a insert. For example, if the schedule is in the table 22:00, at 22:00 every day he will execute the insert.

The problem is that sometimes there may be a delay or something like that and the current time is 22h01, and how it is in the bank 22h00 then will not run the Insert.

I was thinking of putting a break. If, for example, the bank is 22:00 he puts the interval of 1 hour, so if it is 22:00 until 23:00 he executes the Insert. I have no idea how to do, someone can help me with this PHP code?

NOTE: I will put a CRON also to help.

  • 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

4 answers

6


This is a very simple but fully functional way for this type of problem:

  • create a field proximaexecucao in your DB agenda table

In PHP you will use the following algorithm:

  • if the current date/time is greater than or equal to proximaexecucao:

    • do the scheduled operations you want

    • rescues the proximaexecução for:

      • the next day, if you want late to be executed only once

        OR

      • one day more than proximaexecução current, if you want ALL delayed to be executed.

  • if the current date/time is less than proximaexecucao

    • returns without doing anything

This way, you will have the execution running without the risk of double-execution, and without relying on minute comparisons, or the availability of a CRON with very short interval of time.

This solution can be applied for numerous different schedules, with different intervals, provided that each of them has a field proximaexecucao.

And from "toast," it has the advantage of being able to change schedules remotely without touching crontab from the machine, just adjust in DB. For example, put a call via cron every 5 minutes, you can schedule a variety of different events to happen during the day, at various times, all running by the same PHP.

  • Your answer opened my mind to do what I need, thanks!

  • @Alissonacioli just did not detail more for lack of parameters, but I think you got the idea. The beauty of it is that it has no minute accuracy problems, if the cron stops for hours, it keeps working. The secret is that once executed, it creates a condition that is not ambiguous.

2

Logic would be something like this

<?php

$agendamento = 22; // Não vou usar minutos aqui
$horaAtual   = ; // Obtenha a hora via JS

if ( ( $agendamento >= $horaAtual ) || ( $agendamento <= $horaAtual) ) {

    # Execute alguma coisa
}
else
{
    # Ainda não é hora
}

 ?>

2

Cron tasks, or Cron job, have on hosting usually, only ask for information on support, when to learn, install on your pc/note, windows is the common tasks, and linux is cron if I’m not mistaken the name.

Ai Voce says run a script.php from time to time checks something and executes what you want.

I used it for my turn game, every 20 minutes I switched turns, then ran the.php engine.

0

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.