nas
nas

Reputation: 2417

How to execute a command from controller in background?

I have created a command in Symfony. This will run and insert data into the database. I have already tested and it is running fine.

Now my problem is I need to execute this command from the web interface where user clicks on the button and this insertion needs to take place. This insertion will take about 30-45 minutes. So I need to run it in background.

I have heard about Process in Symfony.

So I have created a controller with a route which when called executes following lines.

use Symfony\Component\Process\Process;


$process = new Process('php bin/console app:import:records' . '  > NUL');
$process->run();
return new Response('successfully done', Response::HTTP_OK);

But nothing is happening. It only displays last respnose message.

Can anybody help me ?

Upvotes: 1

Views: 411

Answers (2)

Kirill
Kirill

Reputation: 55

You can use RabbitMQ for this. https://www.rabbitmq.com/tutorials/tutorial-one-php.html Push message with information about action, then recieve that message in consumer and do the work. https://symfony.com/doc/current/messenger.html

Upvotes: 0

X3R0
X3R0

Reputation: 6334

Have a look at this

Extract from the link above....


Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
    try{
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
        }
    }catch(Exception $e){}

    return false;
}

Upvotes: 1

Related Questions