reyesoft/reactive-laravel-jobs

响应式 Laravel 任务

10.0.0 2024-06-23 19:58 UTC

README

安装

composer require reyesoft/reactive-laravel-jobs

特性

  • 同一任务可以基于某些值(如 user_id)进行分组。
  • 延迟时间可以更改(取最后延迟值)。

出色的 Laravel 任务类型

去抖 Laravel 任务

Debounce diagram, from RxJs documentation

仅在延迟值经过并且没有其他任务被触发后,才调度延迟任务。

use Reyesoft\ReactiveLaravelJobs\Debounce\Debounceable;
use Reyesoft\ReactiveLaravelJobs\Debounce\ShouldDebounce;

final class DebouncedNotificationJob implements ShouldDebounce
{
    use Debounceable;
    use Dispatchable;
    use Queueable;

    public $param1 = '';

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

    public function uniqueId()
    {
        return $this->param1;
    }

    public function debouncedHandle(): void
    {
        echo PHP_EOL . $this->param1;
    }
}
DebouncedNotificationJob::dispatchDebounced('You have 1 item.')->delay(5);
DebouncedNotificationJob::dispatchDebounced('You have 2 items.')->delay(5);
DebouncedNotificationJob::dispatchDebounced('You have 3 items.')->delay(5);
sleep(10);
DebouncedNotificationJob::dispatchDebounced('You have 4 items.')->delay(5);
sleep(1);
DebouncedNotificationJob::dispatchDebounced('You have 5 items.')->delay(5);

// Do
You have 3 items.
You have 5 items.

节流 Laravel 任务

调度延迟任务后,忽略后续调度任务一定时间(由延迟值确定),然后在某个时间重复此过程。

Throttle diagram, from RxJs documentation

在 Laravel 9 中,可以使用 唯一任务 完成。

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
 
class ThrottledNotificationJob implements ShouldQueue, ShouldBeUnique
{
    public $param1 = '';

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

    /**
     * The number of seconds after which the job's unique lock
     * will be released.
     */
    public $uniqueFor = 3600;
 
    public function uniqueId()
    {
        return $this->param1;
    }

    public function handle(): void
    {
        echo PHP_EOL . $this->param1;
    }
}
ThrottledNotificationJob::dispatch('You have 1 item.')->delay(5);
ThrottledNotificationJob::dispatch('You have 2 items.')->delay(5);
ThrottledNotificationJob::dispatch('You have 3 items.')->delay(5);
sleep(10);
ThrottledNotificationJob::dispatch('You have 4 items.')->delay(5);
sleep(1);
ThrottledNotificationJob::dispatch('You have 5 items.')->delay(5);

// Do
You have 1 item.
You have 4 items.

测试

composer autofix
composer test