One process at a time PHP


I would like to know if there is a way to create a process queue.

For example, whenever I have performed the file processar.php if it is already running, it would wait to run after the other. Only running when "free";


This sounds very simple.

As you described in the question, I don't think you need threads, queuing, etc. Just create a flag.

When running processo.php create a flag that identifies that it is running.


Coloque no início do arquivo, antes de qualquer execução.
if (!file_exists('processo.txt')) {
    // levanta flag
    file_put_contents(`processo.txt`, 1);
} else {
    exit; // está em execução

aqui faz os paranauê , etc e tal

aqui é o final, quando terminal tudo , remove a flag



A simple tip to improve is to compare the date and time the file was created. If the process takes an average of 10 minutes and in the next run the flag file has more than 10 minutes to live, then something wrong or unexpected has occurred. What to do in this case is up to each person. You can automate it with an email alert, or you can simply ignore and delete the file and generate a new process, generate log, whatever. I can't go into these details because it depends on the business model of each one and trying to explain it here would make the answer too long and tiring, scattering the focus.

about elegance

I believe a solution must be simple, efficient, readable and portable before it is elegant.

The example above shows as simple and portable as possible.

It is portable in the sense that you can use it under any environment (linux, windows, mac) and even on a hosting server with limited resources like shared hosting.

Resource consumption is minimal, much faster than generating a flag in a database.

You can also choose to generate the flag in the operating system environment variables, including linux systems that have features such as posix. However, here we are already creating a complication that in most cases is unnecessary.

Scroll to Top