/[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 430 - (show annotations)
Mon Jul 29 17:30:12 2024 UTC (8 months, 3 weeks ago) by rakin
File MIME type: application/typescript
File size: 1977 byte(s)
refactor: use new queue handler
1 import DiscordClient from "../../client/Client";
2 import { generate as randomstring } from 'randomstring';
3 import { 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 public readonly runOn: number = 0;
15 public readonly id: string;
16 public readonly model: IQueuedJob;
17 protected readonly timeout: NodeJS.Timeout;
18 public readonly guild: string | undefined;
19
20 constructor(protected client: DiscordClient, { runAfter, id, runAt, model }: QueueOptions) {
21 if (runAfter !== 0 && runAfter !== 0 && !runAfter && !runAt) {
22 throw new Error("One of runAfter or runAt must be specified for creating a queue");
23 }
24
25 this.runOn = runAfter ? Date.now() + runAfter : runAt!.getTime();
26 this.id = id ?? randomstring(7);
27 this.model = model;
28 this.guild = model.guild;
29
30 const ms = this.runOn - Date.now();
31
32 this.timeout = setTimeout(async () => {
33 await this.run();
34 await this.finish();
35 }, ms < 0 ? 0 : ms);
36
37 console.log('Queue created: ', this.constructor.name, this.id);
38 }
39
40 get data() {
41 return this.model.data;
42 }
43
44 async finish() {
45 this.client.queueManager.removeQueue(this);
46 console.log("Job complete: ", this.constructor.name);
47 }
48
49 async cancel() {
50 clearTimeout(this.timeout);
51 await this.model.delete();
52 this.client.queueManager.removeQueue(this);
53 }
54
55 abstract execute(data?: { [key: string | number]: any }): Promise<any>;
56
57 async run() {
58 this.completed = true;
59 this.model.delete();
60
61 try {
62 return await this.execute(this.model.data);
63 }
64 catch (e) {
65 console.error(`An error occurred in queue job\nJob ID: ${this.id}`, e);
66 }
67 }
68 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26