user8613418
user8613418

Reputation: 35

PHP detect the first loop of the new day

My solutions works mostly but not really always :) What is the reliable/best solution?

<?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);
}

?>

Upvotes: 0

Views: 441

Answers (2)

DSB
DSB

Reputation: 306

I am not sure of PHP syntaxe, but here is the idea :

<?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);
}

?>

Upvotes: 1

xs0
xs0

Reputation: 2897

There's no need to bother with seconds/time, if all you're interested is the day. In addition, if you check the time twice per loop, there's a chance you miss the switch, so it's more robust to check it exactly once.

<?php

date_default_timezone_set('UTC');
$lastDay = date("Y-m-d");

while (true) {
    $now = date("Y-m-d");
    if ($now !== $lastDay) {
        $lastDay = $now;
        print("First loop of the new day");
    }
    sleep(1);
}

?>

Having said that, I'd use something like cron, if possible..

Upvotes: 2

Related Questions