namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendEmail implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
protected $email;
protected $subject;
protected $message;
/**
* Create a new job instance.
*
* @param string $email
* @param string $subject
* @param string $message
*/
public function __construct(string $email, string $subject, string $message)
{
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Mail::raw($this->message, function ($message) {
$message->to($this->email)->subject($this->subject);
});
}
}
In this example, we have created a SendEmail job class that takes an email address, subject, and message as parameters in the constructor. The handle method is where the actual work of sending the email is done.
Step 2: Dispatch the Job
Once you have created your job class, you can dispatch it to the queue using the dispatch method. This method will add the job to the queue and return immediately, allowing your application to continue processing other requests.
Here is an example of how to dispatch the SendEmail job from the previous step:
Copy code
// Create a new SendEmail job instance
$job = new App\Jobs\SendEmail('recipient@example.com', 'Hello', 'Hello, world!');
// Dispatch the job to the queue
dispatch($job);
Step 3: Process the Queued Jobs
The final step is to process the queued jobs. This is done by running the Laravel queue worker, which listens for new jobs on the queue and runs them as they become available.
To run the queue worker, you can use the following Artisan command:
Copy code
php artisan queue:work
Alternatively, you can run the queue worker in the background using a process manager like Supervisor. This allows the queue worker to run continuously, processing queued jobs as they come in.
That's it! You have now learned how to defer tasks to a queue in Laravel and process them in the background.
No comments:
Post a Comment