PHP sleep()函数基础介绍
PHP sleep() 函数
定义和用法
sleep() 函数用于将代码的执行暂停指定的秒数。 语法格式为 sleep(seconds) seconds 是必需参数,表示需要暂停的时间长度,单位为秒。 返回值说明
如果延迟操作成功完成,该函数返回整数 0;若发生错误,则返回布尔值 false。 错误/异常处理
当传入的 seconds 参数为负数时,该函数会生成一个 E_WARNING 级别的警告信息。
例子
<?php
echo date('h:i:s') . "
"; //暂停 10 秒
sleep(10);//重新开始
echo date('h:i:s');
?>
输出结果示例:
12:00:08 12:00:18
PHP usleep() 函数
定义和用法
usleep() 函数用于将代码的执行暂停指定的微秒数。 语法格式为 usleep(microseconds) microseconds 是必需参数,表示需要暂停的时间长度,单位为微秒。 返回值说明
该函数没有返回值。 提示和注释
注意:在 PHP 5 版本之前,此函数无法在 Windows 操作系统上正常运行。
注意:一微秒等于百万分之一秒(10^-6秒)。 例子
<?php
echo date('h:i:s') . "
";
//延迟 10 描述
usleep(10000000);
//再次开始
echo date('h:i:s');
?>
输出结果示例: 09:23:14 09:23:24
PHP中sleep和unsleep的用法
当你的程序逻辑需要暂停执行几秒钟时,可以使用 sleep 函数。
int sleep ( int $seconds ) 表示程序将在暂停$seconds秒后继续执行。
Returns zero on success, or FALSE on error.成功时返回0,出错时返回false。
If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.
如果调用过程被外部信号中断,该函数将返回一个非零值。在 Windows 平台上,该返回值恒为 192(即 Windows API 中等待 IO 完成常量 WAIT_IO_COMPLETION 的值)。而在其他平台上,返回值则是尚未执行的剩余秒数。
If the specified number of seconds is negative, this function will generate a E_WARNING.
如果传入的参数为负值,函数将产生一个警告错误。
当你需要程序暂停执行小于1秒的时间时,你可以用 usleep
void usleep ( int $micro_seconds )
Delays program execution for the given number of micro seconds.
usleep 的参数单位是微秒,且该函数不返回任何值。
当你需要程序执行单位更小(小于微秒)可以用
time_nanosleep() - Delay for a number of seconds and nanoseconds
如果你希望程序暂停执行到某个时间点,你可以用
time_sleep_until()- Make the script sleep until the specified time