user6592471
user6592471

Reputation: 11

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

Upvotes: 1

Views: 2204

Answers (2)

mrhn
mrhn

Reputation: 18926

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

Upvotes: 0

Rob Fonseca
Rob Fonseca

Reputation: 3819

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

Upvotes: 1

Related Questions