将 sleep() 添加到循环是否可以减轻服务器资源? [英] Does adding sleep() to a loop alleviate server resources?

查看:54
本文介绍了将 sleep() 添加到循环是否可以减轻服务器资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个 PHP 循环,每 60 秒扫描"一次目录,直到找到具有给定名称的文件:

I'm running a PHP loop that 'scans' a directory, every 60 seconds, until a file with a given name is found:

<?php
do {
    if (file_exists("../path/file.txt)) {
        //Do Stuff
        $status = "File Found";
        echo $status;
    } else {
        $status = "File Not Found";
        sleep(60);
    }
} while ($status == "File Not Found");
?>

在这个例子中,删除 sleep() 是否需要更多的服务器资源?

In this example, would removing sleep() require more server resources?

谢谢,

推荐答案

简而言之,是的,但不要担心.

In a nutshell, yes, but don't worry about it.

sleep 正在执行时,您的脚本的 CPU 处理实际上停止了.所以是的,它将减少处理资源.(脚本仍在内存中,所以这些资源仍在使用,但这在现代机器上应该不是问题.)

While sleep is executing, CPU processing of your script virtually stops. So yes, it will alleviate processing resources. (The script is still in memory, so those resources are still used, but that shouldn't be a problem on a modern machine.)

如果您的目标是每 60 秒执行一次,最佳做法是将您的 PHP 设为cron 脚本,并以低优先级运行.

If your goal is to do this every 60 seconds, the best practice would be make your PHP a cron script, and run it at low priority.

nano crontab -e

添加以下内容:

* * * * *   /usr/bin/nice -n 12 php -q /path/file.php

并将 /path/file.php 替换为 PHP 脚本的完整路径.

And replace the /path/file.php with the full path to your PHP script.

编辑脚本的文件权限以允许执行.

Edit your script's file permissions to allow execution.

chmod ug+rwx /path/file.php

(再次将 /path/file.php 替换为您实际 PHP 脚本的完整路径.)

(Again replacing /path/file.php with your actual PHP script's full path.)

最后,如果您打算以这种方式运行它,最好将它们设为 PHP 脚本的前两行:

Lastly, it's a good idea to make these the very first 2 lines in your PHP script, if you intend to run it this way:

#!/usr/bin/php5
<?php

这篇关于将 sleep() 添加到循环是否可以减轻服务器资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆