php 第一次创建文件时延迟4秒 sleep用法

来源:互联网 发布:js最新判断当前浏览器 编辑:程序博客网 时间:2024/06/04 18:41
/**
    ** @name  彩票种类
    *  @uid   帐号uid
    *  @token
    *  @以上参数,付费就有了,这种接口不支持测试,主要获取重庆时时彩最近十条的数据
    */
    public function getssc(){
        //设置接口参数
        $name = 'cqssc';
        $uid = '********';
        $token = '347c028bf659b97b****************************';

        //设置缓存文件目录为插件../data
        $dir = dirname(dirname(__FILE__)).'/data/';
        if (!is_dir($dir)) {
            @mkdir($dir,true);
        }
        //设置缓存文件../data/cqssc.txt;
        $cache_url = $dir.$name.".txt";
        if (!is_file($cache_url)) {
             $file = fopen($cache_url,'w');
             @chmod($file, 0777);
            fclose($file);
            sleep(4);
         }
        //缓存文件(最后更新时间)
        $filemtime = filemtime($cache_url);
        //缓存文件(更新频率设置)//ps:接口时间限制为3秒,坑爹,保险期间,第一次创建文件时延迟4秒,防止并发写入加锁。
        $second = '4';
           /*//////////////////////////////////////
                            $dir = dirname(__FILE__).'/'.time()."second.txt";
                            chmod($dir, 0777);
                            $file = fopen($dir,'w');
                            fwrite($file, time() - $filemtime);
                            fclose($file);
          //////////////////////////////////////*/
        if ( time() - $filemtime >= $second ) {

        //设置参数
            $data = file_get_contents("http://api.caipiaokong.com/lottery/?name=".$name."&format=json&uid=".$uid."&token=".$token."");
        //$data缓存
            $array = json_decode($data,true);
            if(is_array($array)) {
                file_put_contents($cache_url,$data,LOCK_EX);
            }

        }else{
            $data = file_get_contents($cache_url);
            $array = json_decode($data,true);

        }
        return  $data;
        
    }
0 0