问题
I want to do the following: if $start is a multiple of 28, the script will pause for 20 seconds and then continue work.
For this I wrote:
set_time_limit(0);
ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set("Europe/Moscow");
$start = 0;
$end = 2000;
for($start = 0; $start < 20; $start++){
if($start % 28 == 0){sleep(20);echo 'sleep ';}
echo date('H:i:s').'<br>';
}
When I use it, I get:
sleep 14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
14:51:01
So I can see the script is not working right...
Can you please tell me why the script is not working right ?
回答1:
I see that loop:
for($start = 0; $start < 20; $start++){
if($start % 28 == 0){sleep(20);echo 'sleep ';}
echo date('H:i:s').'<br>';
And last value element $start in loop 20.
For loop more taht 1 need use value $start > 56, becose if($start % 28 == 0)
.
For example - 28*2 //for 2 loop.
回答2:
Technically, 0 is a multiple of 28, and your program does work according to that, so I guess that this is simply not what you want. There are two ways I can imagine, maybe in code we understand each other better:
// 1. Sleep after every 28 times outputting current date:
for($i = $start; $i < $end; $i++) {
echo date('H:i:s').'<br>';
if($i % 28 == 27) {
echo 'sleeping...<br>';
sleep(20);
}
}
// 2. Sleep before every 28th time outputting the current date, except the first time:
for($i = $start; $i < $end; $i++) {
if($i != 0) && (($i % 28) == 0)) {
echo 'sleeping...<br>';
sleep(20);
}
echo date('H:i:s').'<br>';
}
If neither of these give you the right idea, then you will have to clarify what exactly you mean.
来源:https://stackoverflow.com/questions/18634546/command-sleep-to-pause-for-20-seconds-if-condition-is-met