首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在没有cron的情况下一天只运行php文件10次?

如何在没有cron的情况下一天只运行php文件10次?
EN

Stack Overflow用户
提问于 2019-05-15 13:11:10
回答 1查看 132关注 0票数 1

我是php的新手,所以请注意这是一个简单的问题。我有一个php脚本,我希望它每天只被执行10次,不超过这一点。我不想使用cron来解决这个问题。有没有办法只在php中做到这一点?

现在,我已经设置了一个计数器,它会在任何人运行脚本时递增1,并仅循环10次。如果超过该值,将显示一条错误消息。

代码语言:javascript
复制
function limit_run_times(){
    $counter = 1;
    $file = 'counter.txt';
    if(file_exists($file)){
         $counter += file_get_contents($file);
    }
    file_put_contents($file,$counter);
    if($counter > 11 ){
        die("limit is exceeded!");
    }
}

我想要一些有效的方法来做到这一点,所以每天脚本只执行10次,这适用于每天,即这个计数器每天被刷新到0,或者有任何其他有效的方法。

EN

回答 1

Stack Overflow用户

发布于 2019-05-15 13:53:22

我更倾向于建议你使用数据库--它更干净,更易于维护。

但是,它也可以通过文件处理来实现。该文件的格式为2019-05-15 1 (用制表符、\t分隔)。获取文件的内容并按explode()拆分值。然后进行比较和检查,并相应地返回值。

代码语言:javascript
复制
function limit_run_times() {
    // Variable declarations
    $fileName = 'my_log.txt';
    $dailyLimit = 10;
    $content = file_get_contents($fileName);
    $parts = explode("\t", $content);
    $date = $parts[0];
    $counter = $parts[1] + 1;

    // Check the counter - if its higher than 10 on this date, return false
    if ($counter > $dailyLimit && date("Y-m-d") === $date) {
        die("Daily executing limit ($dailyLimit) exceeded! Please try again tomorrow.");
    }

    // We only get here if the count is $dailyLimit or less
    // Check if the date is today, if so increment the counter by 1
    // Else set the new date and reset the counter to 1 (as it is executed now)
    if (date("Y-m-d") !== $date) {
        $counter = 1;
        $date = date("Y-m-d");
    }
    file_put_contents($fileName, $date."\t".$counter);
    return true;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56142124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档