-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtask.ts
64 lines (55 loc) · 2.01 KB
/
task.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
import { Duration } from 'ts-duration';
import { WakaQError } from './exceptions.js';
import { WakaQueue } from './queue.js';
import { WakaQ } from './wakaq.js';
export class Task {
public name: string;
public fn: (...args: unknown[]) => Promise<void>;
public wakaq: WakaQ;
public queue?: WakaQueue;
public softTimeout?: Duration;
public hardTimeout?: Duration;
public maxRetries: number;
constructor(
wakaq: WakaQ,
fn: (...args: unknown[]) => Promise<void>,
name?: string,
queue?: WakaQueue | string,
softTimeout?: Duration,
hardTimeout?: Duration,
maxRetries?: number,
) {
if (!name && !fn.name)
throw new Error(`Every WakaQ task needs a name, for ex:\nconst mytask = () => {}\nexport default wakaq.task(mytask);`);
this.fn = fn;
this.name = name ?? fn.name;
this.wakaq = wakaq;
if (queue) this.queue = WakaQueue.create(queue, this.wakaq.queuesByName);
this.softTimeout = softTimeout;
this.hardTimeout = hardTimeout;
if (this.softTimeout && this.hardTimeout && this.hardTimeout <= this.softTimeout)
throw new WakaQError(`Task hard timeout (${this.hardTimeout}) can not be less than or equal to soft timeout (${this.softTimeout}).`);
this.maxRetries = Math.round(maxRetries ?? 0);
}
/*
Run task in the background.
*/
public async delay(...args: any[]) {
return await this.wakaq.enqueueAtEnd(this.name, args, this.queue);
}
/*
Run task in the background after eta.
*/
public async delayWithEta(eta: Duration | Date | number, ...args: any[]) {
const etaVerified = typeof eta === 'number' ? Duration.second(eta) : eta;
return await this.wakaq.enqueueWithEta(this.name, args, etaVerified, this.queue);
}
/*
Run task in the background on all workers.
Only runs the task once per worker parent daemon, no matter the worker's concurrency.
Returns the number of workers the task was sent to.
*/
public async broadcast(...args: any[]): Promise<number> {
return await this.wakaq.broadcast(this.name, args);
}
}