Laravel dispatch queue always intermediately run - laravel

I am trying to dispatch jobs in Laravel into mysql. If I do
dispatch(new SendBroadcastSMS());
or
SendBroadcastSMS::dispatch()->delay(now()->addMinutes(2));
The job always runs intermediately. In my job, I set to sleep 30 seconds and my current controller/page that calls dispatch also waiting for 30 seconds and echo the job return. Why? It should run in the background via worker right? Or I misunderstand with the laravel queue?
My job is like below:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SendBroadcastSMS implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct()
{
}
public function handle()
{
sleep(30);
echo "test";
// dd($this->sendSms("6281517777767","test message"));
//
}
}
my queue driver is database mysql and I also not receieved any row in job table
QUEUE_DRIVER=database

QUEUE_DRIVER is not the property you should set in your .env file.
The correct property is QUEUE_CONNECTION.
QUEUE_CONNECTION=database

Related

How to run MQTT subscribe in the background in Laravel

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

how to broadcast event called by job class

In a Laravel project i am trying to broadcast a event named "closed" via pusher.
In my controller i am calling:
App\Jobs\Closing::dispatch();
My App\Jobs\Closing.php:
<?php
namespace App\Jobs;
use App\Jobs\Close;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class Closing implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(){}
public function handle()
{
$delay = mt_random(10,20);
Close::dispatch()->delay(now()->addSeconds($delay));
}
}
My app\Jobs\Close.php:
<?php
namespace App\Jobs;
use App\Events\Closed;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class Close implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(){}
public function handle()
{
event(new Closed());
}
}
My App\Events\Closed.php:
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class Closed implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(){}
public function broadcastOn()
{
return ['updates'];
}
public function broadcastAs()
{
return 'closed';
}
public function broadcastWith()
{
return ['message' => 'Is Closed!'];
}
}
At this point i need to explain two mandatory situations.
The first one is that i needed to create the job Close class as a job because i needed to delay the execution of the task close. And the only way i can see to make this "delay" is with a Job Class.
The second one is that i have chosen to implement "ShouldBroadcastNow" instead of "ShouldBroadcast" in the event Closed class because i don't want to queue the broadcasting.
Now the problem is that after running:
php artisan queue:work --tries=1
i get in the following output on Command Console:
Processing: App\Jobs\Closing
Processed: App\Jobs\Closing
Processing: App\Jobs\Close
Processing: App\Events\Closed
Failed: App\Events\Closed
Failed: App\Jobs\Close
The first thing that i find weird is that App\Events\Closed goes to queue despite the fact that it implements "ShouldBroadcastNow".
On laravel.log it seems that it occurred a BroadcastException at PusherBroadcaster.php.
But if in the Controller i do:
event(new App\Events\Closed());
the event is properly broadcast via pusher to the client browser.
What is going wrong?
Is there other way do delay the "close" without jobs?
The purpose is to have the following workflow:
1 - We have a event named "closing" an another event named "closed";
2 - We have a task named "close" that occurs "x" seconds after the event "closing", where "x" is a random number;
3 - After the execution of "close" task we broadcast the event "closed".
Thank you for your attention to my problem
Meanwhile i found this is a already known issue (https://github.com/laravel/framework/issues/16478).
It can be solved in two ways:
1 - editing the relevants php.ini files (in my case it was mamp/conf/php7.0.9/php.ini and mamp/bin/php/php7.0.9/php.ini) to point at the location of curl certificate;
2 - editing config/broadcasting.php (setting encrypted to false in pusher options).

Have a queue job always running

I have a queue job that I need to have constantly running.
That means that when the job is finished processing, it should start the job all over again.
How can I do this?
Here's my job:
<?php
namespace App\Jobs;
use App\User;
use App\Post;
use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class PostJob extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function handle()
{
$posts = Post::where('user_id', $this->user->id)
->get();
foreach ($posts as $post) {
// perform actions
}
}
}
Here's the job controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function startPostJob(Request $request, $id)
{
$users = User::all();
foreach ($users as $user) {
$this->dispatch(new PostJob($user));
}
}
}
The queue is meant for one time request, not continuous job running. Your architecture should probably move to more of a cron job setup so you can set intervals to re-run your desired code.
Have a look at the task scheduling documentation here https://laravel.com/docs/5.1/scheduling
The forever running Job, does not sound like the best idea, mostly because it could easily lead to a lot of cpu power being used. But i have done job chaining, which i achieved a certain way, and i think this can help you to solve your problem.
What i usually do, is make the responsibility of a Model specific job, the models responsibility. This will make it easier to invoke from the job.
public class User{
use DispatchesJobs; //must use, for dispatching jobs
...
public function startJob()
{
$this->dispatch(new PostJob($this));
}
}
This will give you the possibility of chaining the jobs together, after the job has ended. Remember to delete the job, after it has finished. And will continue for ever, by creating a new job each time.
public function handle()
{
...
foreach ($posts as $post) {
// perform actions
}
$this->user->startJob();
$this->delete();
}

Send Multiple SMS to users using Jobs

I have around 25K users, I want to send sms for each one of them.
I did the following Job,
<?php
namespace App\Jobs;
use App\User;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use GuzzleHttp\Client;
use GuzzleHttp\Post\PostBodyInterface;
use GuzzleHttp\Exception\ClientException;
class SendSMS extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
public function __construct($user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$client = new \GuzzleHttp\Client(['base_uri' => "example.com"]);
$messageBody = "Message";
$data = ["messageBody"=>$messageBody,
"msisdn"=>$this->user];
$client->request('POST', 'SendSMS',[ 'json'=>$data]);
}
}
And I am dispatching the jobs using JobController
<?php
namespace App\Http\Controllers;
use App\Jobs\SendSMS;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class JobController extends Controller
{
public function sendSMS()
{
$users = User::all();
foreach ($users as $user)
{
$job = (new SendSMS($user->mobile))->onQueue('sms');
$this->dispatch($job);
echo $player->mobile;
echo "<br/>";
}
}
}
And I ran the queue using the command line,
now I have two problems
first : the request is very slow, meaning I wait around 20 seconds for the http request to be done to go for the next user, can I send the request and go to the second user without waiting for the response from the sms api ?
second : can I run the dispatch without actually running the method in the controller, like I want the jobs to be queued using command line for example or any other approach.
Instead of creating a job for each user mobile, create a SendSMSToAllUsers job and your request will be very quick. The SendSMSToAllUsers job will fetch all users an dispatch a new job for each user.
To dispatch without actually running the method in the controller you only need to include the Illuminate\Foundation\Bus\DispatchesJobs trait in any of your classes (artisan commands, queue Jobs, etc...) and use $this->dispatch($job) method.
For better performance either use the async features of Guzzle or dispatch your SMS jobs to multiple queues and run in parallel several queue workers, one for each queue using the parameter --queue=myqueue. Having 25k users is a enough reason for using multiple queues.
For instance, you can create 10 queues: 'sms-0' for phone numbers ending in 0, 'sms-1' for phone numbers ending in 1, ... and so on. Or you can create two queues, 'sms-odd' and 'sms-even' for odd or even numbers.

Query builder in a queued command in Laravel 5

I'm using Laravel 5.0 and I've created a queued command with the Artisan CLI:
php artisan make:command SendEmail --queued
I need to use the DB::table() query builder method into this command, but I'm not able to make it work.
This is an excerpt of my code:
<?php namespace App\Commands;
use App\Commands\Command;
use DB;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class SendEmail extends Command implements SelfHandling, ShouldBeQueued {
use InteractsWithQueue, SerializesModels;
protected $message;
public function __construct($message)
{
$this->message = $message;
}
public function handle()
{
$data = DB::table('structures')->where('id', '=', '1')->first();
// $data is always empty even if database connection works outside the command!!! <-------------------
// no error exception is thrown
}
}
What am I doing wrong?
I found the error. I had to restart the supervisor queue in order the code to be correctly re-read:
supervisorctl
supervisor> restart myQueue

Resources