简体   繁体   中英

Run PHP Script in Background(Without Using Cron)

I want to run following code in Background at certain occurrence:

File A :

// ------------------- Some Code Before Following -----------------------

// send notification to given device token
$notification = new Notification();                    
$notification->sendNotification($token,$count);

// ------------------- Some Code After Above ------------------------

This will called following class :

// 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);
        }
    }
}


?>

When Execution of this class will be completed then it will go back to file A and it will continue execution after sending notification.

But here it will take time to send notification (around 3-5-7 seconds) and for that time user has to wait which is not a good idea .

So what I want to do is that send notification in Background process instead of main thread .So user don't has to wait unnecessarily.

Please note that I don't want to use Cron.

I found that exec/shell_exec/passthru command can help me. But which command I used out of these three commands in this case?

Please Guide me on this. Any help will be appreciated.

passthru("/usr/bin/php /path/to/yourFile.php >> /path/to/log_file.log 2>&1 &");

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the 2>&1 and the & . The 2>&1 is for redirecting errors to the standard IO. And the most important thing is the & at the end of the command string, which tells the terminal not to wait for a response.

There are a few options here:

  • You can fork a separate PHP process with pcntl_fork ( http://php.net/manual/en/function.pcntl-fork.php )
  • You can use a cronjob to check for unsent modifications which you do not want to (you failed to mention WHY, this is why I mention it)
  • You can use a job queue system for it. By far the best solution but takes some time to get started. Gearman is the one I have experience with and that works like a charm.

Follow the instructions here to run a PHP script in the background:

php execute a background process

It requires the use of shell_exec to call the script from File A, so you will have to create a new file for that code to be called. It also assumes you are using linux

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM