S
S
Sorax152018-02-01 21:11:13
PHP
Sorax15, 2018-02-01 21:11:13

Script execution every 5 seconds?

Good evening, please tell me how to write a function, or a piece of code that would be executed every 5 seconds, without task cron in the database

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
OKyJIucT, 2018-02-01
@OKyJIucT

Create such a code and run it through the console.

while(true) {

// какой то код

sleep(5);
}

But there are two nuances that I know of - as soon as you close the console, the script will stop working (it is solved using the so-called screen screen). And the second - the server may have a time limit for executing scripts. On shared hosting, it usually does not exceed 120 seconds.
And one more thing - if the script is not optimized, it will eat up memory until it runs out and the OS crashes it.
Or, alternatively, you can use PM2 for NodeJS - you can keep processes in the background there, you don’t need cron and database, but you need NodeJS.

K
Kolya K, 2018-02-01
@Kolyagrozamorey

Use Cron

A
Antonio Solo, 2018-02-02
@solotony

use processes/threads. The parent spawns a new process every 5 seconds. child processes. handle your tasks.

A
Alexander, 2018-02-02
@AK-VoronM

//Проверяем есть ли запущенные процессы скрипта контроллера
if (getCurrentProcTasks(basename(__FILE__)) > 2) {
    exit("Уже есть запущенные копии контроллера\n");
}

while (true) {
    // do somethings
    // тут легко можно запускать отдельные скрипты, которые выполняются дольше 5 секунд через exec
    sleep(5);
} 

function getCurrentProcTasks($php_file)
{
    $proc = [];
    $cmd = 'ps aux | grep "' . $php_file . '"';
    exec($cmd, $proc);
    $count = count($proc);
    return $count - 2;// 2 - это системные строки, возникающие в результате работы команды grep.
}

Here is a script that can be run from cron every 1-5 minutes to control execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question