dtcn30461 2016-09-24 00: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 01: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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部