On Debian 7.0, the PHP daemon rotates in an infinite loop.

And so, in the top utility, CPU utilization is 97–98%.

I think that the script loads percents because there is a constant access to the file system, that is, the directory is constantly scanned for files. If there are files, the script reads one file at a time, deletes it, and executes something (basically, calls to the external API, there are no space calculations). Then the next file. Basically, the script is chasing idle, that is, there are no files.

How to optimize? But when working with a script, it works instantly, some 1-3 seconds.

  • 2
    So no one writes code. Are you sure that you need to check constantly? Inserting a pause for a couple of seconds of weather will not spoil it, but the processor will greatly unload it. But in general, such things are done with the help of a special thing - inotify . You simply tell the file system what you want to know and it will notify you (for example, about new files or increasing the size of files). - KoVadim
  • Something like inotify was needed. Thank! - zooZooz
  • one
    The delay in 1 second, in top CPU usage does not rise above 0.3% and plus the delay is not felt at all - zooZooz
  • one
    A script spinning in a loop with no time limits will consume memory and processor time. Look for alternatives. At least the same Cron - terantul

1 answer 1

Maybe change the architecture? Look in the direction of Gearman - this is a task manager, there is a client incl. under php .

Instead of monitoring the availability of tasks as files, we will wait for tasks from Gearman.

When a new “task” appears, in addition to creating a file, send the task to Gearman indicating the file. The worker process also rotates in an endless loop awaiting a new task from Gearman.

Winning:

  1. waiting does not load the CPU;
  2. You can perform tasks in multiple threads if the server is multiprocessor;
  3. You can expand the system to multiple servers.