How to run a function in the background in laravel

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

I am stuck in the problem that I call function B in the controller from another function A, and I want the function A calling another function B to not wait for function B to complete. And function B terminates in the background and an independent form of completion by the user of the page and functions. Return.

I searched for it and found that it can be implemented using cron-like jobs in windows, pcntl_fork (), and the Queue function in laravel. I am new to all of this.

Please, help! thank you in advance.

+6
source share
1 answer

since the documentation says http://laravel.com/docs/5.1/queues , first you need to configure the driver - I would start searching for the database at the beginning:

php artisan queue:table php artisan migrate 

then create the job 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 job dispatch manager

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

To do this, you need to run the Queue Listener:

 php artisan queue:listen 

Does it answer?

+8
source

All Articles