PHP Conference Fukuoka 2025

time_nanosleep

(PHP 5, PHP 7, PHP 8)

time_nanosleepEsperar durante un número de segundos y nanosegundos

Descripción

time_nanosleep(int $seconds, int $nanoseconds): array|bool

time_nanosleep() impone un retraso de ejecución de seconds segundos y nanoseconds nanosegundos.

Parámetros

seconds

Debe ser un integer no negativo.

nanoseconds

Debe ser un integer no negativo, inferior a 1000 millones.

Nota: En Windows, el sistema puede esperar más tiempo que el número de nanosegundos dado, según el hardware.

Valores devueltos

Esta función retorna true en caso de éxito o false si ocurre un error.

Si el retraso es interrumpido por una señal, se devolverá un array asociativo con los elementos:

  • seconds: número de segundos restantes en el retraso
  • nanoseconds: número de nanosegundos restantes en el retraso

Ejemplos

Ejemplo #1 Ejemplo con time_nanosleep()

<?php
// ¡Atención! Esto no funcionará como se espera si se devuelve un array
if (time_nanosleep(0, 500000000)) {
echo
"Dormir durante media segundo.\n";
}

// Esto es mejor:
if (time_nanosleep(0, 500000000) === true) {
echo
"Dormir durante media segundo.\n";
}

// Y esto es la mejor forma:
$nano = time_nanosleep(2, 100000);

if (
$nano === true) {
echo
"Dormir durante 2 segundos y 100 microsegundos.\n";
} elseif (
$nano === false) {
echo
"El retraso ha fallado.\n";
} elseif (
is_array($nano)) {
$seconds = $nano['seconds'];
$nanoseconds = $nano['nanoseconds'];
echo
"Interrumpido por una señal.\n";
echo
"Tiempo restante: $seconds segundos, $nanoseconds nanosegundos.";
}
?>

Ver también

  • sleep() - Detiene la ejecución durante algunos segundos
  • usleep() - Detiene la ejecución durante algunas microsegundos
  • time_sleep_until() - Detiene el script durante una duración especificada
  • set_time_limit() - Establece el tiempo máximo de ejecución de un script

add a note

User Contributed Notes 4 notes

up
7
anybody (a) emuxperts.net
19 years ago
Documentation states that "seconds" must be positive. This is not correct, 0 is possible.Rather, "seconds" must be non-negative.
up
6
m at kufi dot net
20 years ago
You should take into account, if you use the function replacement down here, the CPU will be in use of 99% for the time of execution...(A little bit better in this situation is to let the 'full seconds' go by a normal sleep command (makes the thread sleep!, and uses minimum cpu))<?php    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT    function timeWait($microtime)    {//optimizations added by me [start]//sleep the full secondssleep(intval($microtime));//set the microtime to only resleep the last part of the nanos$microtime = $microtime - intval($microtime);//optimizations added by me [end]        $timeLimit = $microtime + array_sum(explode(" ",microtime()));        while(array_sum(explode(" ",microtime())) < $timeLimit)        {/*DO NOTHING*/}        return(true);    }     //THIS IS HOW WE CAN USE IT    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds."; ?>
up
6
fantasysportswire at yahoo dot com
18 years ago
Just glancing at this - and the note from over a year ago with a implementation for windows.. with 5.0.0 and higher it would be simplier to just do something like......

<?php

if (!function_exists('time_nanosleep')) {

function time_nanosleep($seconds, $nanoseconds) {

sleep($seconds);
usleep(round($nanoseconds/100));

return true;

}

}

?>

....off the top of my head - obviously simple enough there should be no mistakes.. but those are the ones that always seem to get ya :( .....
up
4
b dot andrew at shaw dot ca
17 years ago
A response to the note below:Your function is also useless, as the WinNT 32 kernel only functions at a minimum of about 10+ ms (1,000 us), rendering usleep() useless, because usleep uses the C function which is provided by the system (in this case, kernel32.dll).You'll want to use a function that does not rely on the kernel, but rather something made for precise measurement:<?phpfunction usleep_win( $micro_seconds ){    if ( @function_exists( "socket_create" ) && @function_exists( "socket_select" ) )    {        $false = NULL;        $socket = array( socket_create( AF_INET, SOCK_RAW, $false ) );        socket_select( $false, $false, $socket, 0, $micro_seconds );        return true;    }    else    {        return false;    }}?>This function will allow to you sleep for a specified microsecond, although I have measured it to be off by ~5 us.Again, most of this depends on the hardware in your system. If you _REALLY_ need to be precise to < 10 us, you shouldn't be using WinNT anyways!
To Top