PHP 的 sleep() 的实际用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3930736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:29:00  来源:igfitidea点击:

What is a practical use for PHP's sleep()?

phpfunctionsleepusleep

提问by alex

I just had a look at the docs on sleep().

我只是看了看 .doc 上的文档sleep()

Where would you use this function?

你会在哪里使用这个功能?

Is it there to give the CPU a break in an expensive function?

是否可以让 CPU 中断昂贵的功能?

Any common pitfalls?

有什么常见的陷阱吗?

采纳答案by codaddict

One place where it finds use is to create a delay.

它可以使用的一个地方是创建延迟

Lets say you've built a crawler that uses curl/file_get_contentsto get remote pages. Now you don't want to bombard the remote server with too many requests in short time. So you introduce a delay between consecutive requests.

假设您已经构建了一个使用curl/file_get_contents获取远程页面的爬虫。现在您不想在短时间内用太多请求轰炸远程服务器。因此,您在连续请求之间引入了延迟。

sleeptakes the argument in seconds, its friend usleeptakes arguments in microseconds and is more suitable in some cases.

sleep以秒为单位usleep接受参数,它的朋友以微秒为单位接受参数,在某些情况下更合适。

回答by Andy Lester

Another example: You're running some sort of batch process that makes heavy use of a resource. Maybe you're walking the database of 9,000,000 book titles and updating about 10% of them. That process has to run in the middle of the day, but there are so many updates to be done that running your batch program drags the database server down to a crawl for other users.

另一个示例:您正在运行某种会大量使用资源的批处理过程。也许您正在浏览包含 9,000,000 个书名的数据库并更新其中的大约 10%。该过程必须在一天中间运行,但是有太多更新需要完成,以至于运行批处理程序会将数据库服务器拖到其他用户的爬网状态。

So you modify the batch process to submit, say, 1000 updates, then sleepfor 5 seconds to give the database server a chance to finish processing any requests from other users that have backed up.

因此,您修改批处理以提交 1000 次更新,然后sleep在 5 秒钟内让数据库服务器有机会完成处理来自已备份的其他用户的任何请求。

回答by Mischa

Here's a snippet of how I use sleepin one of my projects:

这是我如何在我sleep的一个项目中使用的片段:

foreach($addresses as $address)
{
  $url = "http://maps.google.com/maps/geo?q={$address}&output=json...etc...";
  $result = file_get_contents($url);
  $geo = json_decode($result, TRUE);

  // Do stuff with $geo

  sleep(1);
}

In this case sleephelps me prevent being blocked by Google maps, because I am sending too many requests to the server.

在这种情况下,sleep可以帮助我防止被 Google 地图阻止,因为我向服务器发送了太多请求。

回答by Angry Dan

Old question I know, but another reason for using u/sleep can be when you are writing security/cryptography code, such as an authentication script. A couple of examples:

老问题我知道,但使用 u/sleep 的另一个原因可能是在编写安全/加密代码时,例如身份验证脚本。几个例子:

  1. You may wish to reduce the effectiveness of a potential brute force attack by making your login script purposefully slow, especially after a few failed attempts.
  2. Also you might wish to add an artificial delay during encryption to mitigate against timing attacks. I know that the chances are slim that you're going to be writing such in-depth encryption code in a language like PHP, but still valid I reckon.
  1. 您可能希望通过故意使登录脚本变慢来降低潜在暴力攻击的有效性,尤其是在几次尝试失败之后。
  2. 此外,您可能希望在加密期间添加人为延迟以减轻定时攻击。我知道您将使用 PHP 等语言编写如此深入的加密代码的可能性很小,但我认为仍然有效。

EDIT

编辑

Using u/sleep against timing attacks is not a good solution. You can still get the important data in a timing attack, you just need more samples to filter out the noise that u/sleep adds.

使用 u/sleep 来对抗定时攻击并不是一个好的解决方案。您仍然可以在时序攻击中获得重要数据,您只需要更多的样本来过滤掉 u/sleep 添加的噪声。

You can find more information about this topic in: Could a random sleep prevent timing attacks?

您可以在以下文章中找到有关此主题的更多信息:随机睡眠能否防止定时攻击?

回答by Tom

Another way to use it: if you want to execute a cronjob more often there every minute. I use the following code for this:

另一种使用方法:如果你想每分钟更频繁地执行一个 cronjob。我为此使用以下代码:

sleep(30);
include 'cronjob.php';

I call this file, and cronjob.php every minute.

我每分钟调用这个文件和 cronjob.php。

回答by XediDC

This is a bit of an odd case...file transfer throttling.

这有点奇怪……文件传输节流。

In a file transfer service we ran a long time ago, the files were served from 10Mbps uplink servers. To prevent the network from bogging down, the download script tracked how many users were downloading at once, and then calculated how many bytes it could send per second per user. It would send part of this amount, then sleep a moment (1/4 second, I think) then send more...etc.

在我们很久以前运行的文件传输服务中,文件由 10Mbps 上行链路服务器提供。为了防止网络陷入困境,下载脚本会跟踪一次下载的用户数量,然后计算每个用户每秒可以发送多少字节。它会发送这个数量的一部分,然后睡一会儿(我认为是 1/4 秒)然后发送更多......等等。

In this way, the servers ran continuously at about 9.5Mbps, without having uplink saturation issues...and always dynamically adjusting speeds of the downloads.

通过这种方式,服务器以大约 9.5Mbps 的速度连续运行,没有上行链路饱和问题……并且始终动态调整下载速度。

I wouldn't do it this way, or in PHP, now...but it worked great at the time.

我现在不会这样做,也不会在 PHP 中这样做……但当时它工作得很好。

回答by Fabio Mora

You can use sleep to pause the script execution... for example to delay an AJAXcall by server side or implement an observer. You can also use it to simulate delays.

您可以使用 sleep 来暂停脚本执行...例如延迟服务器端的AJAX调用或实现观察者。您还可以使用它来模拟延迟。

I use that also to delay sendmail() & co. .

我也用它来延迟 sendmail() & co。.

Somebody uses use sleep() to prevent DoS and login brutefoces, I do not agree 'cause in this you need to add some checks to prevent the user from running multiple times.

有人使用 use sleep() 来防止 DoS 和登录暴力破解,我不同意,因为在此您需要添加一些检查以防止用户多次运行。

Check also usleep.

检查也usleep

回答by hohner

I had to use it recently when I was utilising Google's Geolocation API. Every address in a loop needed to call Google's server so it needed a bit of time to receive a response. I used usleep(500000)to give everything involved enough time.

我最近在使用 Google 的 Geolocation API 时不得不使用它。循环中的每个地址都需要调用 Google 的服务器,因此它需要一些时间来接收响应。我曾经usleep(500000)给所有涉及的事情足够的时间。

回答by Octopus

I wouldn't typically use it for serving web pages, but it's useful for command line scripts.

我通常不会用它来提供网页服务,但它对命令行脚本很有用。

$ready = false;
do {
  $ready = some_monitor_function();
  sleep(2);
} while (!$ready);

回答by David

Super old posts, but I thought I would comment as well. I recently had to check for a VERY long running process that created some files. So I made a function that iterates over a cURL function. If the file I'm looking for doesn't exist, I sleep the php file, and check again in a bit:

超级旧的帖子,但我想我也会评论。我最近不得不检查一个非常长时间运行的进程,它创建了一些文件。所以我做了一个迭代 cURL 函数的函数。如果我要查找的文件不存在,我会休眠 php 文件,然后再检查一下:

function remoteFileExists() {
    $curl = curl_init('domain.com/file.ext');

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 404) {
              sleep(7);
              remoteFileExists();
        }
        else{
            echo 'exists'; 
        }
    }

    curl_close($curl);

}

echo remoteFileExists();