- В PHP — sleep(); & ты спишь(); не работает должным образом. Кроме того, возникают проблемы при входе в систему с помощью цикла
- 1 ответ
- sleep
- Описание
- Список параметров
- Возвращаемые значения
- Ошибки
- Примеры
- Смотрите также
- User Contributed Notes 24 notes
- Flush, Sleep + Проблема
- sleep — Откладывает выполнение
- Описание
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Смотрите также
- usleep
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 12 notes
В PHP — sleep(); & ты спишь(); не работает должным образом. Кроме того, возникают проблемы при входе в систему с помощью цикла
У меня 2 проблемы. Вот мой сценарий.
Проблема 1) Я попробовал usleep() и sleep(), сначала он работал несколько раз, выполнил файл, затем задержал время, затем выполнил, затем задержал, и т. Д. Но после 3-го раза это не сработало.
Проблема 2) Если я захожу на «www.xxx.com» без цикла, он работает просто отлично, но когда я помещаю его в цикл, например (допустим, пароль 0002): Логин: ИМЯ ПОЛЬЗОВАТЕЛЯ Пароль: 0000
Логин: USERNAME Пароль: 0001
Логин: USERNAME Пароль: 0002
.. все еще дает мне неверный логин! Любая помощь будет принята с благодарностью:) Спасибо.
1 ответ
Проблема 1) Я думаю, вы достигли максимального времени выполнения, настраиваемого ограничения, которое PHP накладывает на сценарии. PHP-скрипты обычно не являются долгоживущими программами. Они предназначены для быстрого выполнения: один просмотр страницы, один сценарий, так что в качестве меры безопасности (предотвращая атаки типа «отказ в обслуживании») сценарии, которые живут дольше, скажем, 60 секунд, просто прерываются. Проверьте ваш php.ini для этого значения конфигурации.
Проблема 2) Вы закомментировали часть вашего скрипта «submit» и проверили вывод? Я думаю, что ваша программа печатает начало формы только один раз, а затем попробуйте напечатать остальную ее часть 9999 раз. Кроме того, он будет работать только в первый раз, потому что, если вы отправите форму, браузер просто покинет вашу страницу (и ваш сценарий) и не сможет отправить ее во второй раз.
Вы должны использовать CURL для получения ответа от внешнего сайта.
Источник
sleep
(PHP 4, PHP 5, PHP 7, PHP 8)
sleep — Задержка выполнения
Описание
Откладывает исполнение программы на число секунд, указанное в параметре seconds .
Список параметров
Время остановки в секундах.
Возвращаемые значения
Возвращает 0 в случае успешного выполнения или false в случае возникновения ошибки.
Если вызов был прерван сигналом, функция sleep() возвратит значение, не равное нулю. В Windows это значение всегда будет равно 192 (значение константы Windows API WAIT_IO_COMPLETION ). На других платформах возвращаемом значением будет количество секунд, оставшихся до задержки.
Ошибки
Если указанное число секунд в параметре seconds отрицательное, то функция сгенерирует ошибку уровня E_WARNING .
Примеры
Пример #1 Пример использования sleep()
// текущее время
echo date ( ‘h:i:s’ ) . «\n» ;
// ожидание в течениe 10 секунд
sleep ( 10 );
// завершение ожидания
echo date ( ‘h:i:s’ ) . «\n» ;
Этот пример выведет (через 10 секунд)
Смотрите также
- usleep() — Задержка выполнения в микросекундах
- time_nanosleep() — Задержка на заданное число секунд и наносекунд
- time_sleep_until() — Откладывает исполнение скрипта до заданного времени
- set_time_limit() — Ограничение времени выполнения скрипта
User Contributed Notes 24 notes
This may seem obvious, but I thought I would save someone from something that just confused me: you cannot use sleep() to sleep for fractions of a second. This:
( 0.25 ) ?>
will not work as expected. The 0.25 is cast to an integer, so this is equivalent to sleep(0). To sleep for a quarter of a second, use:
re: «mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute.»
Not really — the attacker could do 100 requests. Each request might take 2 seconds but it doesn’t stop the number of requests done. You need to stop processing more than one request every 2 seconds rather than delay it by 2 seconds on each execution.
Maybe obvious, but this my function to delay script execution using decimals for seconds (to mimic sleep(1.5) for example):
/**
* Delays execution of the script by the given time.
* @param mixed $time Time to pause script execution. Can be expressed
* as an integer or a decimal.
* @example msleep(1.5); // delay for 1.5 seconds
* @example msleep(.1); // delay for 100 milliseconds
*/
function msleep ( $time )
<
usleep ( $time * 1000000 );
>
?>
it is a bad idea to use sleep() for delayed output effects as
1) you have to flush() output before you sleep
2) depending on your setup flush() will not work all the way to the browser as the web server might apply buffering of its own or the browser might not render output it thinks not to be complete
netscape for example will only display complete lines and will not show table parts until the
tag arrived
so use sleep if you have to wait for events and don’t want to burn to much cycles, but don’t use it for silly delayed output effects!
I wrote a simple method for sleeping with a float, which also allows you to do milliseconds (via fractional seconds).
function sleepFloatSecs ( $secs ) <
$intSecs = intval ( $secs );
$microSecs = ( $secs — $intSecs ) * 1000000 ;
if( $intSecs > 0 ) <
sleep ( $intSecs );
>
if( $microSecs > 0 ) <
usleep ( $microSecs );
>
>
?>
And testing on my machine it works perfectly:
= [ 0.100 , 0.250 , 0.5 , 1.0 , 1.5 , 2.0 , 2.5 ];
foreach( $x as $secs ) <
$t = microtime ( true );
sleepFloatSecs ( $secs );
$t = microtime ( true ) — $t ;
echo » $secs \t => \t $t \n» ;
>
?>
Output:
=> 0.10017800331116
0.25 => 0.25016593933105
0.5 => 0.50015211105347
1 => 1.0001430511475
1.5 => 1.5003218650818
2 => 2.000167131424
2.5 => 2.5002470016479
?>
Sleep method with parameter in milliseconds :
public static function ms_sleep($milliseconds = 0) <
if($milliseconds > 0) <
$test = $milliseconds / 1000;
$seconds = floor($test);
$micro = round(($test — $seconds) * 1000000);
if($seconds > 0) sleep($seconds);
if($micro > 0) usleep($micro);
>
>
An example of using sleep to run a set of functions at different intervals. This is not a replacement for multi-threading, but it could help someone that wants to do something cheap. You don’t have to use eval(). It is just used as an example. This is different than running a standard 1 second sleep loop, due to sleeping longer does not consume as much CPU.
// current time
echo date ( ‘h:i:s’ ) . «\n» ;
// Add some timers (in seconds) with function calls
$sleeptimers = array();
$sleeptimers [ ‘5’ ][ 0 ][ ‘func’ ] = ‘function_a();’ ;
$sleeptimers [ ’10’ ][ 0 ][ ‘func’ ] = ‘function_b();’ ;
$sleeptimers [ ’15’ ][ 0 ][ ‘func’ ] = ‘function_c();’ ;
// Process the timers
while( true ) <
$currenttime = time ();
reset ( $sleeptimers );
$mintime = key ( $sleeptimers );
foreach( $sleeptimers as $SleepTime => $Jobs ) <
foreach( $Jobs as $JobIndex => $JobDetail ) <
if(!isset( $JobDetail [ ‘lastrun’ ])) <
$sleeptimers [ $SleepTime ][ $JobIndex ][ ‘lastrun’ ] = time ();
if( $SleepTime $mintime ) $mintime = $SleepTime ;
> elseif(( $currenttime — $JobDetail [ ‘lastrun’ ]) >= $SleepTime ) <
eval( $JobDetail [ ‘func’ ]);
$lastrun = time ();
$sleeptimers [ $SleepTime ][ $JobIndex ][ ‘lastrun’ ] = $lastrun ;
$mysleeptime = $SleepTime — ( $currenttime — $lastrun );
if( $mysleeptime 0 ) $mysleeptime = 0 ;
if(( $currenttime — $JobDetail [ ‘lastrun’ ]) $mintime ) $mintime = $mysleeptime ; // account for length of time function runs
echo ‘Sleep time for function ‘ . $JobDetail [ ‘func’ ] . ‘ = ‘ . $mysleeptime . PHP_EOL ;
>
>
>
echo ‘Sleeping for ‘ . $mintime . ‘ seconds’ . PHP_EOL ;
sleep ( $mintime );
>
If you are having issues with sleep() and usleep() not responding as you feel they should, take a look at session_write_close()
as noted by anonymous on comments;
«If the ajax function doesn’t do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall.»
Источник
Flush, Sleep + Проблема
Guest
Flush, Sleep + Проблема
Суть: чат, с flush, sleep и «вечным» циклом. (знаю что ресурсоёмко, но пока так). И вот проблема: на локалхосте (вин98, апач, пхп 4,1) всё работает. Вообще всё. Но в сети (сервер *nix) при показе страницы фрэймов возникает проблема — при обращении к окну дискуссии выводит предыдущие фразы и на куске кода с вечным циклом все прочие фрэймы стопятся, дожидаясь (вечно) пока догрузится дискуссия. Причём дискуссия работает как положено (напрямую пихал в базу сообщения через тестовый скрипт). Пытался делать редирект, собирая значения фрэймов в родительский, и только при загрузке всех фрэймов редиректить на дискуссию, тогда работает — все фрэймы прогружаются, но опять всё виснет и нельзя ни отправить сообщение, ни обновить юзер-лист. Вот в общем как. Есть какие идеи?
И шапка в 1К не помогает (логично) и вообще не понятно. Safe mode отключен. SetTimeLimit = 0.
Кому интересен код — ask.
Поставил пиво кому надо 😉
Guest
Поставил пиво кому надо 😉
Here is a short explanation of the configuration directives.
output_buffering boolean/integer
You can enable output buffering for all files by setting this directive to ‘On’. If you wish to limit the size of the buffer to a certain size — you can use a maximum number of bytes instead of ‘On’, as a value for this directive (e.g., output_buffering=4096).
output_handler string
You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.
Note: You cannot use both mb_output_handler() with ob_inconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
implicit_flush boolean
FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.
When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.
Источник
sleep — Откладывает выполнение
(PHP 4, PHP 5, PHP 7)
sleep — Откладывает выполнение
Описание
Откладывает исполнение программы на число секунд, заданное параметром seconds .
Список параметров
Время остановки в секундах.
Возвращаемые значения
Возвращает 0 при успешном выполнении или FALSE при ошибке.
Если вызов был прерван сигналом, функция sleep() возвратит значение, не равное нулю. В Windows это значение всегда будет равно 192 (значение константы Windows API WAIT_IO_COMPLETION ). На других платформах возвращаемое значение будет числом оставшихся секунд.
Ошибки
Если указанное число секунд в параметре seconds отрицательно, то функция создаст исключение уровня E_WARNING .
Список изменений
| Версия | Описание |
|---|---|
| 5.3.4 | До версии PHP 5.3.4 функция sleep() в Windows всегда возвращала NULL после завершения ожидания, независимо от того было ли прервано выполнение функции или нет. |
Примеры
Пример #1 Пример использования sleep()
// текущее время
echo date ( ‘h:i:s’ ) . «\n» ;
// ожидание в течении 10 секунд
sleep ( 10 );
// завершение ожидания
echo date ( ‘h:i:s’ ) . «\n» ;
Этот пример выведет (через 10 секунд)
Смотрите также
- usleep() — Откладывает выполнение на микросекунды
- time_nanosleep() — Откладывает исполнение на заданное число секунд и наносекунд
- time_sleep_until() — Откладывает исполнение скрипта до заданного времени
- set_time_limit() — Ограничение времени выполнения скрипта
Источник
usleep
(PHP 4, PHP 5, PHP 7, PHP 8)
usleep — Задержка выполнения в микросекундах
Описание
Откладывает выполнение программы на указанное число микросекунд.
Список параметров
Время откладываемого исполнения в микросекундах. Микросекунда — это одна миллионная секунды.
Замечание: Значения больше 1000000 (т.е. ожидание более секунды) могут не поддерживаться операционной системой. Вместо этого используйте sleep() .
Замечание: В Windows система может откладывать исполнение дольше указанного количества микросекунд, в зависимости от аппаратного обеспечения.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Примеры
Пример #1 Пример использования usleep()
// Текущее время
echo date ( ‘h:i:s’ ) . «\n» ;
// ждать 2 секунды
usleep ( 2000000 );
// вернуться к исполнению
echo date ( ‘h:i:s’ ) . «\n» ;
Результат выполнения данного примера:
Смотрите также
- sleep() — Задержка выполнения
- time_nanosleep() — Задержка на заданное число секунд и наносекунд
- time_sleep_until() — Откладывает исполнение скрипта до заданного времени
- set_time_limit() — Ограничение времени выполнения скрипта
User Contributed Notes 12 notes
On both MacOS X and Linux the usleep() call seems to consume CPU cycles, whereas sleep() and time_nanosleep() do not. This was the same on PHP 5.3.29 and 5.5.29.
I used a loop with just a call to sleep/usleep/time_nanosleep, and compared them all with an empty loop. Obviously the empty loop consumed 99% of the CPU, sleep used 0%, usleep used 3% for 1000ms and 6% for 100ms, and time_nanosleep used 0% for both 500ms and 1000ms.
If you’re using Windows then you maybe are in trouble with usleep if you really need to use it.
The Bernie’s microdelay function using fsockopen does not work properly, and the fclose doesn’t help much.
I don’t know if network connections go strange, but I know it does not work since you’ve made more than 2000 — 3000 calls to it, so it’s not a reliable solution in ‘long life’ php scripts, or these are the issues of the microdelay function in my PHP and PHP-GTK applications.
Though another solution should be found, and googling a bit I fount a WinAPI function: Sleep.
So I get with this snippet wich works fine for me, you get milliseconds precission but the more important, it works for long-run scripts and of course, it does not waste any CPU cycles.
// USleep alternative for Windows and PHP4:
$GLOBALS[‘win32api’]->registerfunction(«long Sleep (long dwMillisecods) From kernel32.dll»);
// Now you can call the function from everywhere in your script: $GLOBALS[‘win32api’]->Sleep(milliseconds);
for ($msec = 2000; $msec > 0; $msec = $msec — 125) <
echo «Hi. Next one in $msec msec.\n»;
$GLOBALS[‘win32api’]->Sleep($msec);
>
I have spent DAYS trying to create a reliable usleep()-replacement for Windows.
I have only this to offer:
As commented by someone else already, the gettimeofday() method used below is useless — PHP will use all available CPU power doing nothing.
The fsockopen() method apparently is also useless — as someone else commented, an fclose() was missing in the original post, but this apparently does not solve the problem. After calling the function about 50 or so times, fsockopen() returns immidiately, without any delay — and watching a process monitor in Windows, you can then watch the process taking up increasingly more memory, until eventually PHP aborts (or crashes) when it reaches maximum.
The win32api-method is also a no-go . after calling the Sleep function a few hundred times (during which memory usage will also go up every time due to a memory leak somewhere), PHP will cause an exception and Windows will terminate it.
I have given up — I don’t think there is any viable solution to this problem under PHP 4.
If you need this function, upgrade your project to PHP 5.
Or settle for 1-second delays with the sleep()-function.
These, unfortunately, seem to be your only options.
Note that this function has an overhead!
Example:
for ( $i = 0 ; $i 1000000 ; ++ $i )
<
usleep ( 1 );
>
?>
This block is running about 70 seconds on my server.
Script take about 70 microseconds for every usleep() function call.
To monitor a scripts CPU ussage and avoid any nasty CPU gobbling loops you can use this function (will not work with windows or safe mode) I know it works on FreeBSD:
function phpmon($max)
<
$cmd = `ps -Unobody -r -o%cpu`;
$lines = explode(«\n», $cmd);
$usage = substr($lines[1], 0, strpos($lines[1], «.»));
$sleeprate = 500;
while ($usage >= $max)
<
$cmd = `ps -Unobody -r -o%cpu`;
$lines = explode(«\n», $cmd);
$usage = substr($lines[1], 0, strpos($lines[1], «.»));
usleep($sleeprate);
>
>
where $MAX is the maximum CPU you want the process to consume. e-mail me with any improvements/suggestions.
I have noticed that this consumes a lot of system CPU (at least in my limited testing) possibly from all of the system calls or the huge mathematical functions I used to test the effectiveness of the script.
Dude you are SO the man for that code snippet. It worked like a charm. I just wanted to point out a couple things and offer my own improvement.
1. If you’re like me, you were probably wondering why the socket had to keep being recreated on each call, and why you couldn’t just create a static socket. Its because socket_select assumes you’re passing in a pointer, and will alter the variable on return to reflect the actual sockets that were changed.
2. I couldn’t figure out for the life of me why socket_select wasn’t defined. Its because you hadn’t enabled the right extension in php.ini
Ok so heres my slight improvement. The only real thing I did is use a static variable for the socket, to avoid creating a brand new socket on each call of this function. I’m not sure if socket creation will cause things to crash down the line like the other problems reported on here, but if you ask me better safe then sorry.
function Sleeper($mSec)
<
// For dummies like me who spent 5 minutes
// wondering why socket_create wasn’t defined
if(!function_exists(‘socket_create’)) <
die(«Please enable extension php_sockets.dll»);
>
// So the socket is only created once
static $socket=false;
if($socket===false) <
$socket=array(socket_create(AF_INET,SOCK_RAW,0));
>
$pSock=$socket;
// Calc time
$uSex = $mSec * 1000;
// Do the waiting
socket_select($read=NULL,$write=NULL,$pSock,0,$uSex);
Источник