0

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.

5
  • You'd have to investigate how to run it as a daemon I expect
    – ADyson
    Commented Jun 20, 2023 at 12:07
  • You can use nohup <yourPHPcommand> & to execute the PHP code as a process that can be killed via htop Commented Jun 20, 2023 at 12:34
  • In the past I have used Crontab to execute files on occurence, why this no longer fits? Commented Jun 20, 2023 at 13:10
  • Don't use nohup. Create a systemd unit file shellhacks.com/systemd-service-file-example
    – symcbean
    Commented Jun 20, 2023 at 14:36
  • Marcin wouldnt running it in crontab execute it on a recurring basis? Resulting in multiple durable connections?
    – RodneyUK
    Commented Jun 21, 2023 at 8:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.