A queued job runs out of sight. The person who started it does not know if it still runs, if it is finished, or why it failed. In our client applications, imports, exports and reports often take many minutes. The person who started the work wants to see what happens.
We built the same solution in many projects. Now it is a package: Laravel Background Jobs.
What the package does
Laravel Background Jobs records each unit of work as a background job in the database. Each job has a type, a status, an owner, a log and a meta field.
- It keeps the status of each job: waiting, processing, finished, failed or completed with errors.
- It keeps a log for each job. By default, the log is in the database, so all servers can read it.
- It sends an email to the owner when the job is finished or failed.
- It puts many jobs under one parent run. The run reports one outcome and sends one email.
- It broadcasts each status change, so a page can refresh.
- It has no views and no routes. You build the job pages with the stack that you use.
Install the package
composer require bernskiold/laravel-background-jobs
Publish and run the migrations. They make the background_jobs table and the background_job_logs table.
php artisan vendor:publish --tag=background-jobs-migrations
php artisan migrate
Define the job types
A job type is a case of a backed enum. The enum must implement the BackgroundJobType contract.
use Bernskiold\LaravelBackgroundJobs\Contracts\BackgroundJobType;
enum JobType: string implements BackgroundJobType
{
case ImportReports = 'import_reports';
public function label(): string
{
return match ($this) {
self::ImportReports => __('Import Reports'),
};
}
}
Add the enum to the types list in config/background-jobs.php. A package can also add its own enum with BackgroundJobs::registerTypes().
Make a job and change its status
Use generateFor() to make a job for a model. The owner is the user who is logged in.
use Bernskiold\LaravelBackgroundJobs\Models\BackgroundJob;
$job = BackgroundJob::generateFor($report, JobType::ImportReports, ['file_path' => $path]);
ImportReport::dispatch($job);
In the queued job, change the status and write to the log:
$job->start();
$job->logChannel()->info('Read 1 200 rows.');
$job->finish(); // or $job->fail('The file is empty.');
Let the middleware set the status
You do not have to call start() and finish() yourself. Add the TrackBackgroundJob middleware and the InteractsWithBackgroundJob trait to the queued job.
use Bernskiold\LaravelBackgroundJobs\Concerns\InteractsWithBackgroundJob;
use Bernskiold\LaravelBackgroundJobs\Jobs\Middleware\TrackBackgroundJob;
class ImportReport implements ShouldQueue
{
use InteractsWithBackgroundJob, Queueable;
public function __construct(public BackgroundJob $backgroundJob) {}
public function middleware(): array
{
return [TrackBackgroundJob::andFinish()];
}
public function handle(): void
{
// Only the work. The middleware sets the status.
}
}
The middleware sets the job to processing. If an exception occurs, it fails the job with the message of the exception. The trait also fails the job after a timeout.
Run many jobs as one
A bulk operation can make hundreds of jobs. The owner does not want hundreds of emails. A run puts the jobs under one parent job.
use Bernskiold\LaravelBackgroundJobs\BackgroundJobRun;
$run = BackgroundJobRun::start(JobType::ImportReports, meta: ['item_label' => 'report']);
foreach ($files as $file) {
$child = $run->addChild(null, ['label' => $file->name]);
ImportReport::dispatch($child, $file);
}
$run->seal();
Always call seal(). It tells the run how many children it has. Before this step, the run cannot settle.
When all the children are settled, the run gets its final status. If all the children are finished, the run is finished. If some failed, the run is completed with errors. The run is safe for parallel workers. It counts each child one time, and only one worker can settle it.
Build the job pages
The package has no user interface. It gives the queries, the labels and the events that a page needs. For example, this query gets the jobs of the current user:
BackgroundJob::query()
->mine()
->roots()
->latest()
->paginate();
The package does not have a policy. Your application decides who can see a job, with the abilities viewAny, viewAllJobs, view and update. Each status change broadcasts on private channels. You can use Laravel Echo or Livewire to refresh the page.
When a worker stops
A worker can stop during a job, for example when it uses all its memory. Then nothing changes the status of the job. Schedule two commands to correct this:
Schedule::command('background-jobs:fail-stale')->hourly()->withoutOverlapping();
Schedule::command('background-jobs:reconcile-runs')->everyFifteenMinutes()->withoutOverlapping();
The first command fails jobs that had no update for a long time. Each log entry and each progress update counts as an update. Thus a long job that writes to its log stays alive. The second command settles runs that cannot settle on their own.
A limit to know
The logger writes the log entries in batches. If a job writes to the log in a database transaction, and the transaction rolls back, the entries are lost. To prevent this, set logs.connection to a separate database connection.
Get the package
Laravel Background Jobs is open source, with the MIT license. The code and the full documentation are on GitHub. The documentation also shows retention, temporary files, progress and custom notifications. If you find a problem or have an idea, open an issue. We are happy to hear from you.