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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测