Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent connection in laravel queue worker

I am trying to setup a service on my laravel application with third party library for connecting to provider.

Its code goes as follows

$connection = new CustomConnection();
$connection->refresh();
$connection->sendMessage('[email protected]', ['message'=>'something', 'ttl'=>3600]);
$connection->refresh();
$connection->sendMessage('[email protected]', ['message'=>'something', 'ttl'=>3600]);
$connection->close();

My goal is to keep the connection connected while sending message via laravel queue worker.

Something like if que worker establishes

$connection = new CustomConnection();
$connection->refresh();

Executes $connection->refresh() every 5 seconds & whenever job is added in queue it should execute

$connection->sendMessage('[email protected]', ['message'=>'something', 'ttl'=>3600]);
$connection->refresh();

Block of code.

I have no clue how laravel's core queue works in backend and if I can override it's functionality and how.

Thanks.

like image 718
Ankit Pise Avatar asked Aug 13 '26 02:08

Ankit Pise


1 Answers

In your service provider, register the connection (or a service that uses the connection) as a singleton. Declare this as a dependency for your job, and all your jobs will have the same connection/service instance for the lifetime of the queue worker.

There's no way you can execute $connection->refresh() every fifth second. If the purpose of this call is some kind of heartbeat/healthcheck, listen for the queue-related events and use these instead. A combination of JobProcessing, JobProcessed, JobFailed and Looping will allow you to execute code before and after jobs execute. You can use these to evaluate if you should call $connection->refresh(), like if at least five seconds has passed since last invocation.

There's no event you can use to run code when a job is dispatched.

Do not attempt to override the internal workings of the queue system. There's no promises of backward compatibility between different Laravel releases, and you'll have to keep track of all (possible) subtle changes that are introduced upstream.

like image 147
sisve Avatar answered Aug 16 '26 11:08

sisve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!