我想在某些情况下在后台运行以下代码:
文件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)
user has to wait which is not a good idea
,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
可以帮助我。但是在这种情况下我使用{{1}}哪个命令?
请指导我这个。任何帮助将不胜感激。
答案 0 :(得分:5)
passthru("/usr/bin/php /path/to/yourFile.php >> /path/to/log_file.log 2>&1 &");
这里有一些重要的事情。
首先:把完整路径放到php二进制文件中,因为这个命令将在apache用户下运行,你可能没有像该用户那样设置php命令别名。
Seccond:注意命令字符串末尾的两件事:2>&1
和&
。 2>&1
用于将错误重定向到标准IO。最重要的是命令字符串末尾的&
,它告诉终端不要等待响应。
答案 1 :(得分:0)
这里有几个选项:
答案 2 :(得分:0)
按照此处的说明在后台运行PHP脚本:
php execute a background process
它需要使用shell_exec从文件A调用脚本,因此您必须为要调用的代码创建一个新文件。它还假设您正在使用linux