Search code examples
phpbackgroundfat-free-framework

Execute class method PHP with parameters on the background


I have a class method that sends mails to many recipients, this method receive 2 parameters (one is an integer, and the other is a String), however, when this method is invoked from the main process, the timeout expires and the send no ends. Then, I need that this function (send) run in background, and I need to pass dynamically the parameters, so far i have tried with the exec() command.

I did read somewhere that I could pass the class and method name only putting a space in the command. Therefore, the command that I'm triyng is exec(/usr/bin/php /home/cesar/www/mails.php notices send 1 'Text' > /dev/null); however, this commando doesn't work, beacuse I don't receive the mails.

In this command:

  • mail.php = file script php
  • notices = Class name
  • send = method name
  • 1 = param1
  • 'Text' = param2

Then, I have many questions:

  1. What would the correct way to run this command in background?
  2. How I could pass the parameters dynamically? Do I just do concatenate the command string with my variables?

By the way, this working with "Fat-Free Framework".

Thank you in advance,

Regads from Mexico,


Solution

  • Additionally to Omar's answer, I'm posting here two more solutions which are specific to the framework:

    Solution 1:

    Use the framework's abort() method, to disconnect the HTTP client and continue sending mails in the background:

    $f3->route('GET|POST /myroute',function($f3){
        echo 'Well done Callaghan!'; // message for the client
        $f3->abort(); // stop response here => the client can request something else
        // now we can run extra tasks in the background
        ini_set('max_execution_time',3600);// it may take some time
        $mail->send();
        $mail->send();
        $mail->send();
        ...
    
    });
    

    Solution 2:

    Use the framework's Cron plugin, to schedule background tasks:

    $cron=Cron::instance();
    $cron->set('MassMailing','Mass\Mailing->go','@hourly');
    // Mass\Mailing->go will be executed every hour
    

    You need a web hosting allowing cron jobs to enable this solution.