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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 428 - (hide annotations)
Mon Jul 29 17:30:11 2024 UTC (8 months, 2 weeks ago) by rakin
File MIME type: application/typescript
File size: 1873 byte(s)
refactor: use new queue handler
1 rakin 421 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 rakin 428 get data() {
39     return this.model.data;
40     }
41    
42 rakin 421 async finish() {
43     this.client.queueManager.removeQueue(this);
44     console.log("Job complete: ", this.constructor.name);
45     }
46    
47     async cancel() {
48     clearTimeout(this.timeout);
49     await this.model.delete();
50 rakin 428 this.client.queueManager.removeQueue(this);
51 rakin 421 }
52    
53     abstract execute(data?: { [key: string | number]: any }): Promise<any>;
54    
55     async run() {
56     this.completed = true;
57     this.model.delete();
58 rakin 424
59     try {
60     return await this.execute(this.model.data);
61     }
62     catch (e) {
63     console.error(`An error occurred in queue job\nJob ID: ${this.id}`, e);
64     }
65 rakin 421 }
66     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26