wangzhibo
4 天以前 c19f1f7e21c93d1f13b4f44a8a615f65af577559
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import {
  App,
  Config,
  Inject,
  Logger,
  Provide,
  Scope,
  ScopeEnum,
} from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, LessThan, Repository } from 'typeorm';
import { TaskInfoEntity } from '../entity/info';
import { TaskLogEntity } from '../entity/log';
import { ILogger } from '@midwayjs/logger';
import * as _ from 'lodash';
import { Utils } from '../../../comm/utils';
import { TaskInfoQueue } from '../queue/task';
import { IMidwayApplication } from '@midwayjs/core';
import * as moment from 'moment';
 
/**
 * 任务
 */
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class TaskBullService extends BaseService {
  @InjectEntityModel(TaskInfoEntity)
  taskInfoEntity: Repository<TaskInfoEntity>;
 
  @Logger()
  logger: ILogger;
 
  @InjectEntityModel(TaskLogEntity)
  taskLogEntity: Repository<TaskLogEntity>;
 
  @Inject()
  taskInfoQueue: TaskInfoQueue;
 
  @App()
  app: IMidwayApplication;
 
  @Inject()
  utils: Utils;
 
  @Config('task.log.keepDays')
  keepDays: number;
 
  /**
   * 停止任务
   * @param id
   */
  async stop(id) {
    const task = await this.taskInfoEntity.findOneBy({ id: Equal(id) });
    if (task) {
      const result = await this.taskInfoQueue.getJobSchedulers();
      const job = _.find(result, e => {
        return e.key == task.jobId;
      });
      if (job) {
        await this.taskInfoQueue.removeJobScheduler(job.key);
      }
      task.status = 0;
      await this.taskInfoEntity.update(task.id, task);
      await this.updateNextRunTime(task.jobId);
    }
  }
  /**
   * 移除任务
   * @param taskId
   */
  async remove(taskId) {
    const info = await this.taskInfoEntity.findOneBy({ id: Equal(taskId) });
    const result = await this.taskInfoQueue.getJobSchedulers();
    const job = _.find(result, { key: info?.jobId });
    if (job) {
      await this.taskInfoQueue.removeJobScheduler(job.key);
    }
  }
  /**
   * 开始任务
   * @param id
   * @param type
   */
  async start(id, type?) {
    const task = await this.taskInfoEntity.findOneBy({ id: Equal(id) });
    task.status = 1;
    if (type || type == 0) {
      task.type = type;
    }
    await this.addOrUpdate(task);
  }
  /**
   * 手动执行一次
   * @param id
   */
  async once(id) {
    const task = await this.taskInfoEntity.findOneBy({ id: Equal(id) });
    if (task) {
      await this.taskInfoQueue.add(
        {
          ...task,
          isOnce: true,
        },
        {
          jobId: task.jobId,
          removeOnComplete: true,
          removeOnFail: true,
        }
      );
    }
  }
  /**
   * 检查任务是否存在
   * @param jobId
   */
  async exist(jobId) {
    const info = await this.taskInfoEntity.findOneBy({ jobId: Equal(jobId) });
    if (!info) {
      return false;
    }
    const result = await this.taskInfoQueue.getJobSchedulers();
    const job = _.find(result, e => {
      return e.key == info.jobId;
    });
    return !!job;
  }
  /**
   * 新增或修改
   * @param params
   */
  async addOrUpdate(params) {
    delete params.repeatCount;
    let repeatConf, jobId;
    await this.getOrmManager().transaction(async transactionalEntityManager => {
      if (params.taskType === 0) {
        params.limit = null;
        params.every = null;
      } else {
        params.cron = null;
      }
      await transactionalEntityManager.save(TaskInfoEntity, params);
      if (params.status === 1) {
        const exist = await this.exist(params.jobId);
        if (exist) {
          await this.remove(params.id);
        }
        const { every, limit, startDate, endDate, cron } = params;
        const repeat = {
          every,
          limit,
          jobId: params.jobId,
          startDate,
          endDate,
          cron,
        };
        await this.utils.removeEmptyP(repeat);
        const result = await this.taskInfoQueue.add(params, {
          jobId: params.jobId,
          removeOnComplete: true,
          removeOnFail: true,
          repeat,
        });
        if (!result?.repeatJobKey) {
          throw new Error('任务添加失败,请检查任务配置');
        }
        jobId = result.repeatJobKey;
        repeatConf = result.opts;
      }
    });
    if (params.status === 1) {
      await this.updateNextRunTime(params.jobId);
      await this.taskInfoEntity.update(params.id, {
        repeatConf: JSON.stringify(repeatConf.repeat),
        status: 1,
        jobId,
      });
    }
  }
  /**
   * 删除
   * @param ids
   */
  async delete(ids) {
    let idArr;
    if (ids instanceof Array) {
      idArr = ids;
    } else {
      idArr = ids.split(',');
    }
    for (const id of idArr) {
      const task = await this.taskInfoEntity.findOneBy({ id });
      const exist = await this.exist(task.jobId);
      if (exist) {
        this.stop(task.id);
      }
      await this.taskInfoEntity.delete({ id });
      await this.taskLogEntity.delete({ taskId: id });
    }
  }
 
  /**
   * 保存任务记录,成功任务每个任务保留最新20条日志,失败日志不会删除
   * @param task
   * @param status
   * @param detail
   */
  async record(task, status, detail?) {
    const info = await this.taskInfoEntity.findOneBy({
      id: Equal(task.id),
    });
    if (!info) {
      return;
    }
    await this.taskLogEntity.save({
      taskId: info.id,
      status,
      detail: detail || '',
    });
    // 删除时间超过20天的日志
    await this.taskLogEntity.delete({
      taskId: info.id,
      createTime: LessThan(moment().subtract(this.keepDays, 'days').toDate()),
    });
  }
  /**
   * 初始化任务
   */
  async initTask() {
    try {
      await this.utils.sleep(3000);
      this.logger.info('init task....');
      const runningTasks = await this.taskInfoEntity.findBy({ status: 1 });
      if (!_.isEmpty(runningTasks)) {
        for (const task of runningTasks) {
          const job = await this.exist(task.jobId); // 任务已存在就不添加
          if (!job) {
            this.logger.info(`init task ${task.name}`);
            await this.addOrUpdate(task);
          }
        }
      }
    } catch (e) {}
  }
  /**
   * 任务ID
   * @param jobId
   */
  async getNextRunTime(jobId) {
    let nextRunTime;
    const result = await this.taskInfoQueue.getJobSchedulers();
    const task = _.find(result, e => {
      return e.key === jobId;
    });
    if (task) {
      nextRunTime = new Date(task.next);
    }
    return nextRunTime;
  }
  /**
   * 更新下次执行时间
   * @param jobId
   */
  async updateNextRunTime(jobId) {
    const nextRunTime = await this.getNextRunTime(jobId);
    if (!nextRunTime) {
      return;
    }
    await this.taskInfoEntity.update(
      { jobId },
      {
        nextRunTime,
      }
    );
  }
  /**
   * 详情
   * @param id
   * @returns
   */
  async info(id: any): Promise<any> {
    const info = await this.taskInfoEntity.findOneBy({ id });
    return {
      ...info,
      repeatCount: info.limit,
    };
  }
  /**
   * 刷新任务状态
   */
  async updateStatus(jobId: number) {
    const task = await this.taskInfoEntity.findOneBy({ id: jobId });
    if (!task) {
      return;
    }
    const result = await this.taskInfoQueue.getJobSchedulers();
    const job = _.find(result, { key: task.jobId });
    if (!job) {
      return;
    }
    const nextTime = await this.getNextRunTime(task.jobId);
    if (task) {
      task.nextRunTime = nextTime;
      await this.taskInfoEntity.update(task.id, task);
    }
  }
  /**
   * 调用service
   * @param serviceStr
   */
  async invokeService(serviceStr) {
    if (serviceStr) {
      const arr = serviceStr.split('.');
      const service = await this.app
        .getApplicationContext()
        .getAsync(_.lowerFirst(arr[0]));
      for (let i = 1; i < arr.length; i++) {
        const child = arr[i];
        if (child.includes('(')) {
          const [methodName, paramsStr] = child.split('(');
          const params = paramsStr
            .replace(')', '')
            .split(',')
            .map(param => param.trim());
          if (params.length === 1 && params[0] === '') {
            return service[methodName]();
          } else {
            const parsedParams = params.map(param => {
              try {
                return JSON.parse(param);
              } catch (e) {
                return param; // 如果不是有效的JSON,则返回原始字符串
              }
            });
            return service[methodName](...parsedParams);
          }
        }
      }
    }
  }
}