-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathexecutor.ts
82 lines (73 loc) · 1.97 KB
/
executor.ts
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
import { Logger } from '@nestjs/common';
import { IGlobalConfig } from './interfaces/global-config.interface';
export class Executor {
private timer;
private currentRetryCount = 0;
private logger = new Logger('ScheduleModule');
constructor(private readonly configs: IGlobalConfig) {}
async execute(
jobKey: string,
callback: () => Promise<Stop> | Stop,
tryLock: Promise<TryLock> | TryLock,
): Promise<Stop> {
let release;
if (typeof tryLock === 'function') {
try {
release = await tryLock(jobKey);
if (!release) {
return false;
}
} catch (e) {
this.logger.error(`Try lock job ${jobKey} fail. ${e.message}`, e.stack);
return false;
}
}
const result = await this.run(jobKey, callback);
try {
typeof release === 'function' ? release() : void 0;
} catch (e) {
this.logger.error(`Release lock job ${jobKey} fail.`, e.stack);
}
return result;
}
private async run(
jobKey: string,
callback: () => Promise<Stop> | Stop,
): Promise<Stop> {
try {
const result = await callback();
this.clear();
return result;
} catch (e) {
this.logger.error(`Execute job ${jobKey} fail.`, e.stack);
if (
this.configs.maxRetry !== -1 &&
this.currentRetryCount < this.configs.maxRetry
) {
if (this.timer) {
clearTimeout(this.timer);
}
await new Promise(resolve => {
this.timer = setTimeout(async () => {
this.currentRetryCount++;
resolve(await this.run(jobKey, callback));
}, this.configs.retryInterval);
});
return false;
} else {
this.logger.error(
`Job ${jobKey} already has max retry count.`,
e.stack,
);
return false;
}
}
}
private clear() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
this.currentRetryCount = 0;
}
}
}