How can I run a PHP stomp file as a background process?

44 views Asked by At

I have installed Apache ActiveMQ and PECL Stomp, enabling the stomp.so extension on PHP.

I have written a PHP file which connects to a TCP address and successfully consumes messages from the topic, when run through the Ubuntu terminal command line using command sudo php ./myfile.php

After running this command, the connection works fine, and consumes messages, outputting the payload to a file.txt.

My question is, how can I run this in the background, constantly consuming the data, writing to file, without end unless it disconnects / fails?

The purpose of this file will be to connect and receive a specific file at 0600hrs on a Friday, when a certain file is published by the end server. My problem is getting the file to stay running. In the past I have used Crontab to execute files on occurence, how to I run this and get it to stay connected? Thanks

The Code:

<?php
        $server = "tcp://url:61618";
        $user = "";
        $password = "";
        $channel = "channel";

        $con = new Stomp($server, $user, $password, array('client-id' => 'tsr'));
        if (!$con) {
                die('Connection failed: ' . stomp_connect_error());
        }

        $con->subscribe("/topic/" . $channel, array('activemq.subscriptionName' => 'tsr'));

        while($con){
        if ($con->hasFrame()){
                $msg = $con->readFrame();
                foreach (json_decode($msg->body) as $event) {
                        $response = print_r($event, true);
                        file_put_contents('file.txt', $response, FILE_APPEND);
                }
                $con->ack($msg);
        }
}
die('Connection lost: ' . time());
$con->disconnect();

?>

Established the file as a "durable subscription", expecting the file to continue running after execution. After execution of the file, the console freezes (expected as I am not echoing any output to the console), but the file works fine.

Using activeMQ 5.18.1 on Ubuntu, PECL Stomp with OpenSSL.

0

There are 0 answers