/[sudobot]/trunk/src/utils/structures/Queue.ts
ViewVC logotype

Contents of /trunk/src/utils/structures/Queue.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 421 - (show annotations)
Mon Jul 29 17:30:09 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 1622 byte(s)
refactor: queue jobs
1 import DiscordClient from "../../client/Client";
2 import { v4 as uuid } from 'uuid';
3 import QueuedJob, { IQueuedJob } from "../../models/QueuedJob";
4
5 export interface QueueOptions {
6 runAfter?: number;
7 id?: string;
8 runAt?: Date;
9 model: IQueuedJob;
10 }
11
12 export default abstract class Queue {
13 protected completed = false;
14 protected runOn: number = 0;
15 public readonly id: string;
16 protected readonly model: IQueuedJob;
17 protected readonly timeout: NodeJS.Timeout;
18
19 constructor(protected client: DiscordClient, { runAfter, id, runAt, model }: QueueOptions) {
20 if (runAfter !== 0 && runAfter !== 0 && !runAfter && !runAt) {
21 throw new Error("One of runAfter or runAt must be specified for creating a queue");
22 }
23
24 this.runOn = runAfter ? Date.now() + runAfter : runAt!.getTime();
25 this.id = id ?? uuid();
26 this.model = model;
27
28 const ms = this.runOn - Date.now();
29
30 this.timeout = setTimeout(async () => {
31 await this.run();
32 await this.finish();
33 }, ms < 0 ? 0 : ms);
34
35 console.log('Queue created: ', this.constructor.name, this.id);
36 }
37
38 async finish() {
39 this.client.queueManager.removeQueue(this);
40 console.log("Job complete: ", this.constructor.name);
41 }
42
43 async cancel() {
44 clearTimeout(this.timeout);
45 await this.model.delete();
46 }
47
48 abstract execute(data?: { [key: string | number]: any }): Promise<any>;
49
50 async run() {
51 this.completed = true;
52 this.model.delete();
53 return await this.execute(this.model.data);
54 }
55 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26