Laravel 13的任务批次可以统一记录一组队列作业的进度,并在作业配合检查时响应取消。下面适用于PHP 8.6上的既有异步队列项目,以两个独立报表分片文件为例,展示Batchable作业、批次派发和进度查询;取消不会强制终止已经进入业务处理的代码。
准备批次表和异步队列
1、项目需已配置可用的异步队列连接,并准备对应队列表或redis服务。生成并执行批次表迁移,迁移前按项目正式流程检查数据库变更。
php artisan make:queue-batches-table php artisan migrate php artisan queue:work

Laravel任务批次表与Batchable作业说明
2、worker要连接到派发使用的同一连接与队列。sync连接会在请求里执行,不能拿它声称已经实现并行后台处理。
编写会响应取消的作业
1、在app/Jobs/WriteReportPart.php建立作业。以下rows使用演示数组,正式数据应按授权范围分片读取,并让重复执行写入同一业务分片位置。
<?php
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
class WriteReportPart implements ShouldQueue {
use Batchable, Queueable;
public function __construct(public int $part, public array $rows) {}
public function handle(): void {
$batch = $this->batch();
if (!$batch || $batch->cancelled()) return;
$path = 'batch-reports/' . $batch->id . '/' . $this->part . '.json';
$ok = Storage::disk('local')->put($path,
json_encode($this->rows, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
if (!$ok) throw new \RuntimeException('报表分片写入失败');
}
}派发并只读查看批次
1、在已授权的控制器或受控命令中派发,保存返回的批次ID。两个作业的完成顺序不固定,不以添加顺序推定文件已全部生成。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
use App\Jobs\WriteReportPart;
use Illuminate\Support\Facades\Bus;
$batch = Bus::batch([
new WriteReportPart(1, [['id' => 1, 'amount' => 10]]),
new WriteReportPart(2, [['id' => 2, 'amount' => 20]]),
])->name('演示报表分片')->dispatch();
$batchId = $batch->id;
// 后续受控查询时,使用已经保存的真实ID:
$current = Bus::findBatch($batchId);
if (!$current) throw new RuntimeException('批次不存在');
echo json_encode(['id' => $current->id, 'progress' => $current->progress(),
'failed' => $current->failedJobs, 'cancelled' => $current->cancelled()], JSON_THROW_ON_ERROR);
Laravel批次派发和回调的执行范围
2、需要取消时对同一批次调用$current->cancel()。处理时间较长的作业还应在安全检查点再次判断取消,不能认为设置标志会抢占正在执行的进程。
立即学习“PHP免费学习笔记(深入)”;

Laravel取消批次及作业配合检查的示例
批次失败、结束和所有作业成功是不同状态。Web进度接口必须确认该批次属于当前用户;Batchable不自动完成业务授权。批次回调会序列化,不能在其中引用$this;作业内也应避免触发数据库隐式提交的语句。


















