AllordEmad AllordEmad - 21 days ago 7
PHP Question

Code start and end in specific time

Hi guys i have a code that start and end in specific time, my code is work fine but i want to use this code in data that loop
for example i'll pot names in loop and i want for each one to start and end in specific time:

this is my code:

<?php
date_default_timezone_set('America/New_York');
$time = date('Y:m:d H:i:s');
$timestart = date('Y:m:d H:i:s'); //time start
$timeend = '2016:11:17 10:56:00'; //time end

if($time >= $timeend){
echo "time end";
}else{
echo 'untel end time';
}


$now = new DateTime();
$future_date = new DateTime($timeend);
$interval = $future_date->diff($now);
?>


and i want to know how to use it with loop data?

thanks.

Answer

You can use EV or Event extension or implement by loop. I prefer EV extension to this task

And create timer for example:

// Required create variable!
$w = new EvTimer($needWorkedSeconds, $repeatAfterSecond, function ($w) {
    echo "iteration = ", Ev::iteration(), PHP_EOL;
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

More read here!

OR use event (but i prefer event to work with socket):

$base = new \EventBase();
$e = \Event::timer($base, function($n) use (&$e) {
    echo "$n seconds elapsed\n";
    if($isTimeEndNow)
    {
         $e->delTimer();
    }
}, $repeatAfterSecond);
$e->addTimer($repeatAfterSecond);
$base->loop();

More read here!

Or you can try while, for example:

while(true)
{
    if($isTimeEndNow)
    {
         break;
    }
    sleep($repeatAfterSecond);
}

In example i use undeclareted variable:

$repeatAfterSecond - seconds to next iteration or next call
$isTimeEndNow - this is: time() > $endTimestamp
$needWorkedSeconds - this is seconds: time_start - time_end

ATTENTIONAL!!! Be Careful! I think you make mistake, if you want use MySQL and if you need die script in concrete time. Review your algorithm!!!