Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make function run in background in laravel

I am developing a website in Laravel 5.0 and hosted in Windows Server2012.

I am stuck at a problem which is I am calling a function B in controller from another function A and I want that the function A which calls the another function B does not wait for the completion of function B . And Function B gets completes in the background and independent form user termination of page and function A return .

I have searched this and found that this can be implemented through cron like jobs in windows, pcntl_fork() and Queue functionality in laravel. I am beginner in all this.

Please help! thanks in advance.

like image 264
Nilesh Avatar asked Jul 16 '15 10:07

Nilesh


1 Answers

as the documentation states http://laravel.com/docs/5.1/queues, first you need to setup the driver - i would go for database in the beginning :

php artisan queue:table

php artisan migrate

then create the Job that you want to add to the queue

<?php

namespace App\Jobs;

use App\User;
use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendEmail extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function handle(Mailer $mailer)
    {
        $mailer->send('emails.hello', ['user' => $this->user], function ($m) {
            //
        });
    }
}

then in the Controller dispatch the job

<?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
{
    /**
     * Send a reminder e-mail to a given user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $sendEmailJob = new SendEmail($user);

        // or if you want a specific queue

        $sendEmailJob = (new SendEmail($user))->onQueue('emails');

        // or if you want to delay it

        $sendEmailJob = (new SendEmail($user))->delay(30); // seconds

        $this->dispatch($sendEmailJob);
    }
}

For that to work, you need to be running the Queue Listener:

php artisan queue:listen

Does that answer?

like image 119
UX Labs Avatar answered Sep 19 '22 19:09

UX Labs