在后台执行带参数的class方法PHP

Execute class method PHP with parameters on the background

我有一个 class 方法可以向许多收件人发送邮件,这个方法接收 2 个参数(一个是整数,另一个是字符串),但是,当从 main 调用这个方法时进程,超时到期并且发送没有结束。然后,我需要在后台使用这个函数(发送)运行,我需要动态传递参数,到目前为止我已经尝试使用 exec() 命令。

我确实在某处读到我可以传递 class 和方法名称,只需要在命令中放置一个 space。因此,我正在尝试的命令是 exec(/usr/bin/php /home/cesar/www/mails.php notices send 1 'Text' > /dev/null);然而,这个突击队不起作用,因为我没有收到邮件。

在这个命令中:

那么,我有很多问题:

  1. 运行 在后台执行此命令的正确方法是什么?
  2. 如何动态传递参数?我只是将命令字符串与我的变量连接起来吗?

顺便说一句,这与 "Fat-Free Framework" 一起工作。

提前谢谢你,

来自墨西哥的 Regads,

exec 需要一个字符串参数,你还必须使用 escapeshellarg 转义你发送的文本,所以整个命令应该看起来像这可以工作:

 $text_to_send = "Hello World , "
 exec("/usr/bin/php /home/cesar/www/mails.php notices send 1 " . $text_to_send . " > /dev/null");

现在你 mail.php 你可以像这样接收文本 :

$text_to_send = $argv[5];

除此之外,您还有其他方法可以在后台发送电子邮件,例如,您可以将文本存储在数据库中 table,然后创建一个 cron 作业,让我们假设 1 分钟检查是否table 中有要发送的任何文本,然后在从数据库发送后删除该文本。

另一种选择是使用库创建用于发送电子邮件的后台作业,例如 php-resquegearman .

除了 Omar 的回答之外,我在这里发布了另外两个特定于框架的解决方案:

解决方案一:

使用框架的abort()方法,断开HTTP客户端并在后台继续发送邮件:

$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();
    ...

});

方案二:

使用框架的 Cron 插件来安排后台任务:

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

您需要允许 cron jobs 启用此解决方案的虚拟主机。