imtigger/laravel-job-status

Laravel Job Status

1.2.0 2020-09-19 16:43 UTC

This package is auto-updated.

Last update: 2024-08-26 15:52:02 UTC


README

Latest Stable Version Total Downloads Build Status License

Laravel 扩展包,用于追踪派送到 QueueJob 进度、状态和结果。

  • 队列名称、尝试次数、状态以及创建/更新/开始/完成的时间戳。

  • 进度更新,具有任意当前/最大值和自动计算的百分比

  • 处理带有异常信息的失败任务

  • 自定义输入/输出

  • 原生 Eloquent 模型 JobStatus

  • 支持 Laravel 包含的所有驱动(null/sync/database/beanstalkd/redis/sqs)

  • 此包故意不提供用于显示 Job 进度的任何 UI。

    如果您有这样的需求,请参阅 laravel-job-status-progress-view

    或使用 JobStatus 模型自行实现

要求

  • PHP >= 7.1
  • Laravel/Lumen >= 5.5

安装

Laravel 的安装

Lumen 的安装

用法

在您的 Job 中,使用 Trackable 特性并在构造函数中调用 $this->prepareStatus()

<?php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Imtigger\LaravelJobStatus\Trackable;

class TrackableJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels, Trackable;

    public function __construct(array $params)
    {
        $this->prepareStatus();
        $this->params = $params; // Optional
        $this->setInput($this->params); // Optional
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $max = mt_rand(5, 30);
        $this->setProgressMax($max);

        for ($i = 0; $i <= $max; $i += 1) {
            sleep(1); // Some Long Operations
            $this->setProgressNow($i);
        }

        $this->setOutput(['total' => $max, 'other' => 'parameter']);
    }
}

在您的 Job 分发器中,调用 $job->getJobStatusId() 以获取 $jobStatusId

<?php

class YourController {
    use DispatchesJobs;

    function go() {
        $job = new TrackableJob([]);
        $this->dispatch($job);

        $jobStatusId = $job->getJobStatusId();
    }
}

$jobStatusId 可用于其他地方以检索作业状态、进度和输出。

<?php
$jobStatus = JobStatus::find($jobStatusId);

故障排除

调用未定义的方法 ...->getJobStatusId()

Laravel 提供多种派发作业的方式。并非所有方法都返回您的 Job 对象,例如

<?php
YourJob::dispatch(); // Returns PendingDispatch instead of YourJob object, leaving no way to retrive `$job->getJobStatusId();`

如果您真的需要以这种方式派发作业,则需要工作区:创建自己的键

  1. 创建迁移,向 job_statuses 表添加额外的键。

  2. 在您的作业中,生成自己的唯一键并将其传递到 prepareStatus();$this->prepareStatus(['key' => $params['key']]);

  3. 以另一种方式查找 JobStatus:$jobStatus = JobStatus::whereKey($key)->firstOrFail();

状态直到事务提交才更新

从版本 >= 1.1 开始,添加了对专用数据库连接的支持。

因此,即使在应用程序事务中,JobStatus 更新也可以立即保存。

阅读设置步骤 6 以获取说明。

文档

<?php
// Job protected methods (Call from your Job)
$this->prepareStatus();                           // Must be called in constructor before any other methods
$this->setProgressMax(int $v);                    // Update the max number of progress
$this->setProgressNow(int $v);                    // Update the current number progress
$this->setProgressNow(int $v, int $every);        // Update the current number progress, write to database only when $v % $every == 0
$this->incrementProgress(int $offset)             // Increase current number progress by $offset
$this->incrementProgress(int $offset, int $every) // Increase current number progress by $offset, write to database only when $v % $every == 0
$this->setInput(array $v);                        // Store input into database
$this->setOutput(array $v);                       // Store output into database (Typically the run result)

// Job public methods (Call from your Job dispatcher)
$job->getJobStatusId();                       // Return the primary key of JobStatus (To retrieve status later)

// JobStatus object fields
var_dump($jobStatus->job_id);                 // String (Result varies with driver, see note)
var_dump($jobStatus->type);                   // String
var_dump($jobStatus->queue);                  // String
var_dump($jobStatus->status);                 // String [queued|executing|finished|retrying|failed]
var_dump($jobStatus->attempts);               // Integer
var_dump($jobStatus->progress_now);           // Integer
var_dump($jobStatus->progress_max);           // Integer
var_dump($jobStatus->input);                  // Array
var_dump($jobStatus->output);                 // Array, ['message' => $exception->getMessage()] if job failed
var_dump($jobStatus->created_at);             // Carbon object
var_dump($jobStatus->updated_at);             // Carbon object
var_dump($jobStatus->started_at);             // Carbon object
var_dump($jobStatus->finished_at);            // Carbon object

// JobStatus generated fields
var_dump($jobStatus->progress_percentage);    // Double [0-100], useful for displaying progress bar
var_dump($jobStatus->is_ended);               // Boolean, true if status == finished || status == failed
var_dump($jobStatus->is_executing);           // Boolean, true if status == executing
var_dump($jobStatus->is_failed);              // Boolean, true if status == failed
var_dump($jobStatus->is_finished);            // Boolean, true if status == finished
var_dump($jobStatus->is_queued);              // Boolean, true if status == queued
var_dump($jobStatus->is_retrying);            // Boolean, true if status == retrying

注意

$jobStatus->job_id 的结果因驱动而异