1

I am trying to put MQTT subscribe into a job saved in the database, but I get an error message that the job has failed instead of running for an infinite time. I would like to know if my approach is even possible and if there are any better alternatives to my problem.

My code

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use PhpMqtt\Client\Facades\MQTT;

class StartSub implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function handle()
    {
        $mqtt = MQTT::connection();
        $mqtt->subscribe('topic', function (string $topic, string $message) {
            echo sprintf('Received QoS level 1 message on topic [%s]: %s',
                $topic, $message);
        }, 1);
        $mqtt->loop(true);
    }
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Luke
  • 11
  • 3

1 Answers1

0

The answer is pretty simple. Although I do not know if it is 100% correct. After further investigation I found out that my code was failing because of time out. So i just had to put a public $timeout = 0;.

Luke
  • 11
  • 3
  • 1
    You should not be calling `$mqtt->subscribe()` from within an HTTP request or a queue job since the call to `$mqtt->loop()` will block the process infinitely afterwards. In case of an HTTP request, this means the caller will never receive a response and in case of a queue job, you are blocking the entire worker. Instead, use an Artisan command and a service like supervisor to ensure the command is restarted if it exits. – Namoshek May 06 '22 at 16:47