Let's see ... the idea would be that you had the code running so I could tell you how to run it using a cronjob, but you do not even have the code running, so we're going to work with a model.
Since:
- you have an endpoint (e.g.
http://api.com/endpoint
)
- a token (e.g.
080042cad6356ad5dc0
)
- the API waits for a Bearer-type token
- the API responds with JSON
You can use curl to bring you the data. Let's say the following script is called " bring_data.php ":
<?php
$ch = curl_init();
$headers = [
'Content-Type: application/json',
'Authorization: Bearer 080042cad6356ad5dc0'
];
curl_setopt($ch, CURLOPT_URL, 'http://api.com/endpoint');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$respuesta = curl_exec($ch);
curl_close($ch);
$resultado = json_decode($respuesta, true);
That php script can take charge of inserting the result in the database (here I am instantiating a connection with an invented class and inserting with an invented method:
<?php
$conexion = new TipoDeConexion($usuario, $password, $host, $pulpos_pegajosos);
... petición curl...
insertaResultado($resultado);
That script already does everything you need, you just have to run it by command line like:
php trae_datos.php
Instead of executing it during the cycle of a request generated by ajax or by another request from the frontend.
To automate the execution of the script, you put it in a cron, executing:
crontab -e
The structure of the crontab file is:
m h dom mon dow command
(minuto) (hora) (dia_del_mes) (mes) (dia_de_la_semana) (comando a ejecutar)
So if you want to run your script every day at 9:30 AM you would add to the cron a line that contains:
30 9 * * * cd /home/gals/proyecto && /usr/bin/php trae_datos.php >> datos.log
Where 30 9 * * *
means "every day at 9:30 AM no matter what month we are, or on what day of the month or on what day of the week".
The rest is to tell him to navigate to the directory where the script is and then execute it. Note that I am using /usr/bin/php
because the cron does not always have access to your PATH and it is better to give it the full path. Finally, I send the output (any echo
executed in the script) to datos.log
. This is an optional step but you will need it if one day you do not have fresh data and you want to know what went wrong.