Search code examples
phpcroncron-task

Turning PHP API call into cron job and accessing returned values


My goal is to run the below php script every 10 minutes and then be able to access the $temp and $icon values in a website front-end:

$api_endpoint = 'https://api.forecast.io/forecast/';
$api_key = get_field('forecast_api_key', 'option');
$latitude = get_field('latitude', 'option');
$longitude = get_field('longitude', 'option');
$units = 'auto';
$lang = 'en';
$exclude = 'minutely,hourly,daily,alerts,flags';

// Build API call and parse data

$url = $api_endpoint.$api_key.'/'.$latitude.','.$longitude.'?units='.$units.'&exclude='.$exclude;
$response = file_get_contents($url);
$weather_data = json_decode($response, true);

// Output to front-end

$temp = round($weather_data['currently']['temperature']);
$icon = $weather_data['currently']['icon'];

Could someone please explain on a high level what the best approach would be to do this? I need to limit the number of API calls per day to the endpoint and as far as I understand, this script should be executed as a cron task, but am not sure how to get at the variable values from a website in /var/www/.

If I have overlooked a simpler way (i.e. not using cron) to limit the number of calls per period time, I would be interested in alternative suggestions too.

The server environment is an Ubuntu 14.04 LTS VPS.

Many thanks for your help.


Solution

  • I don't think you need a cron task at all, unless you need the returned value for other purposes (conducting some calculations in background process for example)

    What I suggest is to write a function, which makes the API call and stores the result in to the database. You can implement a simple caching logic to avoid the API call on every page load. Pseudo code might look like this:

    function getAPIresult(){
       //Idea is to check for record in local db, before making the API call
       //you can define the time schedule, AKA cache validity time as you want
       $result = mysql_query("select from api_results where date='today'");
       if($result){
          return $result; // if valid record is found, use it on your website
       }
       else{
         return setAPIResult();
       }
    }
    
    function setAPIResult(){
       //API CALL goes here and inserts the result into the database
       .....
       $weather_data = json_decode($response, true);
       $result = mysql_insert('inserto into api_results ... values($weather_data)');
       return $result; // insert and return the value
    }