如何在特定时间间隔内运行PHP脚本(例如每天一次)?

Adr*_*ana 10 php autorun

我有一个PHP脚本,通过http读取一个文件(该文件在其他域上).我想每天只阅读一次或两次此文件,而不是每次刷新网站时都连接到该文件. 除了使用cron之外还有其他方法吗? 我不想使用cron因为我更喜欢在脚本本身设置这种行为..因此它很灵活,所以我可以在任何地方使用它而无需每次都设置cron.谢谢

cOl*_*le2 12

过去,当我无法访问cron时,我已经完成了这种事情:

$lastRunLog = '/path/to/lastrun.log';
if (file_exists($lastRunLog)) {
    $lastRun = file_get_contents($lastRunLog);
    if (time() - $lastRun >= 86400) {
         //its been more than a day so run our external file
         $cron = file_get_contents('http://example.com/external/file.php');

         //update lastrun.log with current time
         file_put_contents($lastRunLog, time());
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您不能或不想使用cron,只有在访问页面时才可以更新它.您可以缓存HTTP请求的结果,只有在缓存超过一天或您选择的任何时间间隔时才在页面上加载它.