Nahouto
Nahouto

Reputation: 1385

Sleep breaks the script

I want simply to set a sleep in a loop. But it doesn't work as expected

for ($i = 1; $i <= 6; $i++) {
    echo $i;
    sleep(1);
}

if the loop takes more than 5 seconds. It doesn't work (don't print at all).

I tested it in Teh Playground, and this error appears :

Execution took longer than 5 seconds, sent SIGTERM and terminated

Edit : Modifying set_time_limit doesn't change anything...

It seems it's related to my server's config...

Upvotes: 0

Views: 192

Answers (4)

crimson589
crimson589

Reputation: 1306

I don't think there's anything wrong with your code, do you get any error on your own server?

I tried your code and it worked properly, just copy pasted it.

I think the error you're getting is just TehPlayground not liking something executing for more than 5 seconds because I set the for loop to less than 4 and didn't get the error message.

for ($i = 1; $i <= 4; $i++) {
    echo $i;
    sleep(1);
}

Upvotes: 0

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

SIGTERM is the signal that is typically used to administratively terminate a process and its triggered by tehplayground's some server settings which is not related to PHP

Because your program executes amount of time allowed on tehplayground, There is nothing wrong with your code.

I ran it on my server it works fine.

To increase the time limit on your server

For runtime

ini_set('max_execution_time', 60); //60 secs

Change this on php.ini for permanent change

; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 300

Setting it to 0 means there's no time limit.

Upvotes: 1

Amila K.
Amila K.

Reputation: 199

This works fine when I ran it in my local machine. I think your script execution getting timed out at Teh Playground when it takes more than 5 seconds to execute.

Upvotes: 0

ino
ino

Reputation: 2581

Set the second condition of for bigger, ie $i <= 60;

for ($i = 1; $i <= 60; $i++) {
    echo $i;
    sleep(1);
}

The condition says "loop the block as many times as the $i is less than 6".
for is a function,

  1. first you define value of $i equal to 1, $i = 1;
  2. second you define the condition, ie do the block while $i is less then 6, $i <= 6;
  3. third on each loop increase the $i by one (the double plus), $i++

Upvotes: 0

Related Questions