• Stars
    star
    473
  • Rank 92,832 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Monitoring Laravel Jobs with your Database

Laravel Queue Monitor

Latest Stable Version Total Downloads License GitHub Build Status

This package offers monitoring like Laravel Horizon for database queue.

Features

  • Monitor jobs like Laravel Horizon for any queue
  • Handle failing jobs with storing exception
  • Monitor job progress
  • Get an estimated time remaining for a job
  • Store additional data for a job monitoring
  • Retry jobs via the UI

Installation

See Upgrade Guide if you are updating to 4.0

composer require romanzipp/laravel-queue-monitor

See romanzipp/Laravel-Queue-Monitor-Nova for Laravel Nova resources & metrics.

Configuration

Copy configuration & migration to your project:

php artisan vendor:publish --provider="romanzipp\QueueMonitor\Providers\QueueMonitorProvider" --tag=config --tag=migrations

Migrate the Queue Monitoring table. The table name can be configured in the config file or via the published migration.

php artisan migrate

Usage

To monitor a job, simply add the romanzipp\QueueMonitor\Traits\IsMonitored Trait.

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use romanzipp\QueueMonitor\Traits\IsMonitored; // <---

class ExampleJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use IsMonitored; // <---
}

Important! You need to implement the Illuminate\Contracts\Queue\ShouldQueue interface to your job class. Otherwise, Laravel will not dispatch any events containing status information for monitoring the job.

Web Interface

You can enable the web UI by setting the ui.enabled to true configuration value.

Publish frontend assets:

php artisan vendor:publish --provider="romanzipp\QueueMonitor\Providers\QueueMonitorProvider" --tag=assets

See the full configuration file for more information.

Preview Preview

Commands

artisan queue-monitor:stale

This command mark old monitor entries as stale. You should run this command regularly in your console kernel.

Arguments & Options:

  • --before={date} The start date before which all entries will be marked as stale
  • --beforeDays={days} The relative amount of days before which entries will be marked as stale
  • --beforeInterval={interval} An interval date string before which entries will be marked as stale
  • --dry Dry-run only

artisan queue-monitor:purge

This command deletes old monitor models.

Arguments & Options:

  • --before={date} The start date before which all entries will be deleted
  • --beforeDays={days} The relative amount of days before which entries will be deleted
  • --beforeInterval={interval} An interval date string before which entries will be deleted
  • --queue={queue} Only purge certain queues (comma separated values)
  • --only-succeeded Only purge succeeded entries
  • --dry Dry-run only

Either the before or beforeDate arguments are required.

Advanced usage

Progress

You can set a progress value (0-100) to get an estimation of a job progression.

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class ExampleJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $this->queueProgress(0);

        // Do something...

        $this->queueProgress(50);

        // Do something...

        $this->queueProgress(100);
    }
}

Chunk progress

A common scenario for a job is iterating through large collections.

This example job loops through a large amount of users and updates its progress value with each chunk iteration.

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class ChunkJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $usersCount = User::count();

        $perChunk = 50;

        User::query()
            ->chunk($perChunk, function (Collection $users) use ($perChunk, $usersCount) {

                $this->queueProgressChunk($usersCount‚ $perChunk);

                foreach ($users as $user) {
                    // ...
                }
            });
    }
}

Progress cooldown

To avoid flooding the database with rapidly repeating update queries, you can set override the progressCooldown method and specify a length in seconds to wait before each progress update is written to the database. Notice that cooldown will always be ignore for the values 0, 25, 50, 75 and 100.

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class LazyJob implements ShouldQueue
{
    use IsMonitored;

    public function progressCooldown(): int
    {
        return 10; // Wait 10 seconds between each progress update
    }
}

Custom data

This package also allows setting custom data in array syntax on the monitoring model.

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class CustomDataJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $this->queueData(['foo' => 'Bar']);
        
        // WARNING! This is overriding the monitoring data
        $this->queueData(['bar' => 'Foo']);

        // To preserve previous data and merge the given payload, set the $merge parameter true
        $this->queueData(['bar' => 'Foo'], true);
    }
}

In order to show custom data on UI you need to add this line under config/queue-monitor.php

'ui' => [
    ...

    'show_custom_data' => true,

    ...
]

Only keep failed jobs

You can override the keepMonitorOnSuccess() method to only store failed monitor entries of an executed job. This can be used if you only want to keep failed monitors for jobs that are frequently executed but worth to monitor. Alternatively you can use Laravel's built in failed_jobs table.

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class FrequentSucceedingJob implements ShouldQueue
{
    use IsMonitored;

    public static function keepMonitorOnSuccess(): bool
    {
        return false;
    }
}

Retrieve processed Jobs

use romanzipp\QueueMonitor\Models\Monitor;

$job = Monitor::query()->first();

// Check the current state of a job
$job->isFinished();
$job->hasFailed();
$job->hasSucceeded();

// Exact start & finish dates with milliseconds
$job->getStartedAtExact();
$job->getFinishedAtExact();

// If the job is still running, get the estimated seconds remaining
// Notice: This requires a progress to be set
$job->getRemainingSeconds();
$job->getRemainingInterval(); // Carbon\CarbonInterval

// Retrieve any data that has been set while execution
$job->getData();

// Get the base name of the executed job
$job->getBasename();

Model Scopes

use romanzipp\QueueMonitor\Models\Monitor;

// Filter by Status
Monitor::failed();
Monitor::succeeded();

// Filter by Date
Monitor::lastHour();
Monitor::today();

// Chain Scopes
Monitor::today()->failed();

Tests

The easiest way to execute tests locally is via Lando. The Lando config file automatically spins up app & database containers.

lando start

lando phpunit-mysql
lando phpunit-postgres

Upgrading

License

The MIT License (MIT). Please see License File for more information.


This package was inspired by gilbitron's laravel-queue-monitor which is not maintained anymore.

More Repositories

1

Laravel-SEO

SEO package made for maximum customization and flexibility
PHP
294
star
2

Laravel-Twitch

Twitch Helix API PHP Wrapper for Laravel
PHP
97
star
3

GetBetter

Get Better static website
JavaScript
34
star
4

PHP-Slim-Pagination

Example pagination for slimphp/Slim
19
star
5

Laravel-Validator-Pizza

A PHP Laravel Wrapper for the validator.pizza API
PHP
19
star
6

is-odd-or-even

Determines if a given number is odd or even.
JavaScript
17
star
7

Laravel-Turnstile

🔥 Cloudflare Turnstile CAPTCHA package for Laravel
PHP
13
star
8

Laravel-Blockade

A simple but highly customizable package for preventing access to private or WIP Laravel projects.
PHP
10
star
9

Laravel-Model-Doc

Generate PHPDoc comments for Laravel Models
PHP
8
star
10

DTO

A strongly typed Data Transfer Object without magic for PHP 8
PHP
7
star
11

Laravel-Skeleton

Domain Driven Laravel Skeleton with strong type hinting
PHP
7
star
12

Laravel-Migration-Generator

⚠️ WIP ⚠️ - Generate Laravel migration files from existing databases
PHP
7
star
13

Laravel-DTO

Laravel Data-Transfer-Object
PHP
6
star
14

Laravel-Console-List-Columns

Quick Command to list DB Table Columns & Information
PHP
5
star
15

Bingo

Create public shareable interactive bingo games with unlimited players. No account required. No ads. No bullshit.
PHP
5
star
16

Laravel-Env-Diff

Create a visual Diff of multiple .env files
PHP
5
star
17

PHP-CS-Fixer-Config

Personal PHP-CS-Fixer wrapper & Custom rules & preset management inlcuding PHPStorm integration
PHP
4
star
18

Sprinter

Standalone simple networking monitoring using pings in SQLite storage
JavaScript
3
star
19

HSFD-WebApp

ignore plz
Vue
3
star
20

Laravel-Make-File-Permissions

This package automatically applies unix file permissions after the 'artisan make:' command.
PHP
3
star
21

Laravel-Previously-Deleted

Store selected attributes of Models before deletion
PHP
3
star
22

product-notifier

Product availability notifier for Nike & Zalando
Go
1
star
23

Wanderer

Nomad Deployer with Web GUI & API - GitHub Action included
HTML
1
star