在php中执行时跳过部分代码以增加执行时间

时间:2019-01-17 18:13:06

标签: php ajax

我正在执行一个简单的php脚本,以使用php插入大约10-20个字段,并且效果很好,执行时间约为40毫秒。但是现在,当我集成短信和快速邮件服务时,大约需要执行8.40到10.2秒。我想延长执行时间,怎么办呢?

  if(isset($_POST["submit"])){
  $hostname='localhost';
  $username='root';
  $password='';

  try {
  $dbh = new PDO("mysql:host=$hostname;dbname=college",$username,$password);

  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
  $sql = "INSERT INTO students (student_name, student_email, student_city)
  VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
    if ($dbh->query($sql)) {
      echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";

      // this part of code takes a lot to execute
      $hello_form_submit_body = 'test mail';
      send_mail($hello_form_submit_subject, $_POST["stu_email", $_POST["stu_name"], $hello_form_submit_body, 'test mail', $hello_id, 'hello');

      /*send sms*/
      $sms_body = "Thank You, Your hello application has been submitted with ORDER ID (".$data_hello['hello_order_no']."), please complete your payment here (".$button_link.")";
      sms($data_hello['hello_mobile_no'], $sms_body, 'OLhello');


    }
    else{
      echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
    }

    $dbh = null;
  }
  catch(PDOException $e) {
    echo $e->getMessage();
  }

}



/*Functions Used*/
function sms($number, $message, $sender_id){
  //code to send sms
}

function send_mail($subject, $to, $to_name, $body, $sender_name, $id, $service){
  //swift mailer code to send mail using smtp
}

有什么方法可以跳过该代码的执行时间并继续执行其余的操作,例如我不在乎是否发送了短信或是否发送了邮件,我只想通过短信来增加执行时间和邮件发送功能已执行,或者建议使用类似的方式,例如我将向执行该功能的文件发送请求,而我将继续执行而无需等待该功能的响应。

1 个答案:

答案 0 :(得分:0)

虽然有很多解决方案,但最简单的解决方案可能是分叉您的进程,让孩子发送邮件而死,而父级继续处理其余脚本

$sms_body = "Thank You, Your hello application has been submitted with ORDER ID (".$data_hello['hello_order_no']."), please complete your payment here (".$button_link.")";
  if(!pcntl_fork())
  {sms($data_hello['hello_mobile_no'], $sms_body, 'OLhello');
  exit;
  }