[英]Run PHP Script in Background(Without Using Cron)
我想在某些情况下在后台运行以下代码:
文件A:
// ------------------- Some Code Before Following -----------------------
// send notification to given device token
$notification = new Notification();
$notification->sendNotification($token,$count);
// ------------------- Some Code After Above ------------------------
这将称为以下课程:
// Here I am sending notification to given device token (APNS Push Notification)
<?php
class Notification
{
public function sendNotification($token,$count)
{
if(strlen($token)%16 == 0)
{
// set Device token
$deviceToken = $token;
$passphrase = 'xxxxx';
$badge = $count;
// Displays alert message here:
$message = 'Hello! There.';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err,$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo("Connected to APNS.");
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'badge' => $badge,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo("\n\nMessage not delivered.\n\n");
else
echo("\n\nMessage successfully delivered.\n\n");
// Close the connection to the server
fclose($fp);
}
}
}
?>
当此类的Execution
completed
it will go back to file A
并continue execution after sending notification.
但是在这里take time to send notification (around 3-5-7 seconds)
会take time to send notification (around 3-5-7 seconds)
,在这段时间内user has to wait which is not a good idea
。
所以我想做的是send notification in Background process instead of main thread
中send notification in Background process instead of main thread
。这样用户就不必不必要地等待。
Please note that I don't want to use Cron.
我发现exec/shell_exec/passthru command
可以为我提供帮助。 但是在这种情况下,我out of these three commands
中使用out of these three commands
哪个命令?
请为此指导我。 任何帮助将不胜感激。
passthru("/usr/bin/php /path/to/yourFile.php >> /path/to/log_file.log 2>&1 &");
这里有一些重要的事情。
首先:将完整路径放置到php二进制文件中,因为此命令将在apache用户下运行,并且您可能没有在该用户中设置类似php的命令别名。
第二步:请注意命令字符串末尾的两件事: 2>&1
和&
。 2>&1
用于将错误重定向到标准IO。 最重要的是命令字符串末尾的&
,它告诉终端不要等待响应。
这里有一些选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.