ProjectKeywordAiTask.php
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace App\Models\Project;
use App\Helper\Arr;
use App\Models\Base;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class ProjectKeywordAiTask extends Base
{
//设置关联表名
protected $table = 'gl_project_keyword_ai_task';
const STATUS_PENDING = 0;
const STATUS_SUCCESS = 1;
const STATUS_FAIL = 2;
public static function add_task($project_id){
$task = self::where('project_id', $project_id)->where('status', self::STATUS_PENDING)->first();
if($task){
throw new \Exception('该项目有未执行的任务,请勿重复添加');
}
$model = new self();
$model->project_id = $project_id;
$model->save();
Redis::lpush('projectKeywordAiTask', $project_id);
}
public static function getPendingTask(){
//有其他任务 就取其他任务 没有其他任务运行未结束的任务
$project_id = Redis::rpop('projectKeywordAiTask');
$data = [];
if($project_id){
$data = self::where('status', self::STATUS_PENDING)->where('project_id', $project_id)->orderBy('id', 'asc')->first();
}
if($data){
return $data;
}
return self::where('status', self::STATUS_PENDING)->orderBy('id', 'asc')->first();
}
/**
* 重试任务
* @param $id
* @param $remark
* @author zbj
* @date 2023/11/9
*/
public static function retry($id, $remark)
{
DB::beginTransaction();
try {
//行锁 避免脏读写
$data = self::where('id', $id)->lockForUpdate()->first();
$data->retry = $data->retry + 1;
if ($data->retry > 3) {
$data->status = self::STATUS_FAIL;
}else{
$data->status = self::STATUS_PENDING;
}
$data->remark = mb_substr($remark, 0, 250);
$data->save();
DB::commit();
} catch (\Exception $e) {
DB::rollback();
Log::error('project_keyword_ai_task retry error:' . $e->getMessage());
}
}
/**
* 完成
* @param $id
* @param $update_rows
* @author zbj
* @date 2023/11/9
*/
public static function finish($id, $update_rows){
DB::beginTransaction();
try {
//行锁 避免脏读写
$data = self::where('id', $id)->lockForUpdate()->first();
$data->status = self::STATUS_SUCCESS;
$data->update_rows = $update_rows;
$data->save();
DB::commit();
} catch (\Exception $e) {
DB::rollback();
Log::error('project_keyword_ai_task finish error:' . $e->getMessage());
}
}
}