PHP检测新一天的第一个循环

时间:2017-11-21 09:45:49

标签: php date datetime time

我的解决方案大多数工作但并非总是如此:)什么是可靠/最佳解决方案?

<?php

date_default_timezone_set('UTC');
$seconds_today = time() - strtotime('today');

while (true) {
    if ($seconds_today > time() - strtotime('today')) {
        print('First loop of the new day');
    }
    $seconds_today = time() - strtotime('today');
    sleep(1);
}

?>

2 个答案:

答案 0 :(得分:2)

如果您感兴趣的是当天,那么就没有必要打扰秒/时间。另外,如果你检查每个循环两次的时间,那么你就有可能错过开关,所以检查它一次就更健壮了。

const

话虽如此,如果可能的话,我会使用像cron这样的东西..

答案 1 :(得分:1)

我不确定PHP语法,但这是一个想法:

<?php

date_default_timezone_set('UTC');
$previous_day = 0;

while (true) {
    if ($previous_day != strtotime('today')) {
        print('First loop of the new day');
        $previous_day = strtotime('today');
    }
    sleep(1);
}

?>