ProjectUpdateTdk.php
3.5 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
/**
* @remark :
* @name :ProjectUpdateTdk.php
* @author :lyh
* @method :post
* @time :2023/11/8 11:18
*/
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 ProjectUpdateTdk extends Base
{
//设置关联表名
protected $table = 'gl_project_update_tdk';
const STATUS_PENDING = 0;
const STATUS_SUCCESS = 1;
const STATUS_FAIL = 2;
/**
* 新建任务
* @param $project_id
* @throws \Exception
* @author zbj
* @date 2023/11/9
*/
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('updateSeoTdk', $project_id);
}
/**
* 获取待处理任务
* @return mixed
* @author zbj
* @date 2023/11/9
*/
public static function getPendingTask(){
//有其他任务 就取其他任务 没有其他任务运行未结束的任务
$project_id = Redis::rpop('updateSeoTdk');
$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_update_tdk retry error:' . $e->getMessage());
}
}
/**
* 完成
* @param $id
* @param $update_data
* @author zbj
* @date 2023/11/9
*/
public static function finish($id, $update_data){
DB::beginTransaction();
try {
//行锁 避免脏读写
$data = self::where('id', $id)->lockForUpdate()->first();
$data->status = self::STATUS_SUCCESS;
foreach($update_data as $field => $item){
$old_date = Arr::s2a($data->$field);
$new_data = [];
foreach($item as $k=>$v){
if($k == 'total_page'){
$new_data[$k] = $v;
}else{
$new_data[$k] = $v + ($old_date[$k] ?? 0);
}
}
$data->$field = $new_data;
}
$data->save();
DB::commit();
} catch (\Exception $e) {
DB::rollback();
Log::error('project_update_tdk finish error:' . $e->getMessage());
}
}
}