perf: task进程添加执行记录

This commit is contained in:
kuaifan
2022-11-16 11:27:55 +08:00
parent 99fc12e8c4
commit c1be894d35
14 changed files with 127 additions and 5 deletions

View File

@@ -1,6 +1,9 @@
<?php
namespace App\Tasks;
use App\Models\TaskWorker;
use App\Module\Base;
use Carbon\Carbon;
use Hhxsv5\LaravelS\Swoole\Task\Task;
/**
@@ -9,6 +12,20 @@ use Hhxsv5\LaravelS\Swoole\Task\Task;
*/
abstract class AbstractTask extends Task
{
protected int $twid = 0;
public function __construct(...$params)
{
$row = TaskWorker::createInstance([
'args' => [
'params' => $params,
'class' => get_class($this)
],
]);
if ($row->save()) {
$this->twid = $row->id;
}
}
/**
* 开始执行任务
@@ -25,11 +42,12 @@ abstract class AbstractTask extends Task
*/
final public function handle()
{
TaskWorker::whereId($this->twid)->update(['start_at' => Carbon::now()]);
//
try {
$this->start();
} catch (\Throwable $e) {
$this->failed("start", $e);
}
}
@@ -38,8 +56,11 @@ abstract class AbstractTask extends Task
*/
final public function finish()
{
TaskWorker::whereId($this->twid)->update(['end_at' => Carbon::now()]);
//
try {
$this->end();
TaskWorker::whereId($this->twid)->delete();
} catch (\Throwable $e) {
$this->failed("end", $e);
}
@@ -54,5 +75,13 @@ abstract class AbstractTask extends Task
{
info($type);
info($e);
//
TaskWorker::whereId($this->twid)->update(['error' => Base::array2json([
'time' => Carbon::now(),
'type' => $type,
'code' => $e->getCode(),
'file' => $e->getFile(),
'message' => $e->getMessage(),
])]);
}
}