dtcn30461 2016-09-24 08:52
浏览 47
已采纳

将PHP API调用转换为cron作业并访问返回的值

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.

  • 写回答

1条回答 默认 最新

  • doumei1908 2016-09-24 09:15
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起