Skip to content

Commit

Permalink
refactor n better signatures for task scheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jul 6, 2024
1 parent 4821057 commit 2014e0e
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 38 deletions.
5 changes: 2 additions & 3 deletions src/core/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
return eventModule({ type: EventType.Discord, ...mod, });
}


export function scheduledTask(i : ScheduledTask) {
return i
export function scheduledTask(ism: ScheduledTask) {
return ism
}

46 changes: 26 additions & 20 deletions src/core/structures/default-services.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { LogPayload, Logging, ErrorHandling } from '../interfaces';
import { ScheduledTask } from '../../types/core-modules';
import type { LogPayload, Logging, ErrorHandling, Disposable } from '../interfaces';
import { CronJob } from 'cron';

/**
Expand Down Expand Up @@ -41,21 +42,28 @@ export class DefaultLogging implements Logging {
}


export class TaskScheduler {
private __tasks: Map<string, CronJob> = new Map();
export class TaskScheduler implements Disposable {
private __tasks: Map<string, CronJob<any, any>> = new Map();

schedule(taskName: string, cronExpression: string | Date, task: () => void, tz: string| undefined) {
if (this.__tasks.has(taskName)) {
schedule(uuid: string, task: ScheduledTask, deps: Dependencies) {
if (this.__tasks.has(uuid)) {
throw Error("while scheduling a task \
found another task of same name. Not scheduling " +
taskName + "again." );
found another task of same name. Not scheduling " +
uuid + "again." );
}
try {
const job = CronJob.from({ cronTime: cronExpression, onTick: task, timeZone: tz });
job.start();
this.__tasks.set(taskName, job);
const onTick = async function(this: CronJob) {
task.execute({
deps, id: uuid,
lastTimeExecution: this.lastExecution,
nextTimeExecution: this.nextDate().toJSDate()
})
}
const job = CronJob.from({ cronTime: task.trigger, onTick, timeZone: task.timezone });
job.start();
this.__tasks.set(uuid, job);
} catch (error) {
throw Error(`while scheduling a task ${taskName} ` + error);
throw Error(`while scheduling a task ${uuid} ` + error);
}
}

Expand All @@ -69,17 +77,15 @@ export class TaskScheduler {
return false;
}

private restartTask(taskName: string): boolean {
const job = this.__tasks.get(taskName);
if (job) {
job.start();
return true;
}
return false;
}

get tasks(): string[] {
return Array.from(this.__tasks.keys());
}

dispose() {
for(const [id,] of this.__tasks){
this.kill(id);
this.__tasks.delete(id);
}
}

}
2 changes: 1 addition & 1 deletion src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export async function callInitPlugins(_module: Module, deps: Dependencies, emit?
return module
}

async function callPlugins({ args, module, deps, params }: ExecutePayload) {
export async function callPlugins({ args, module, deps, params }: ExecutePayload) {
let state = {};
for(const plugin of module.onEvent??[]) {
const result = await plugin.execute(...args, { state, deps, params, type: module.type });
Expand Down
15 changes: 3 additions & 12 deletions src/handlers/tasks.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,17 @@
import * as Files from '../core/module-loading'
import { UnpackedDependencies } from "../types/utility";
import { ScheduledTask } from "../types/core-modules";
import type { ScheduledTask } from "../types/core-modules";
import { CronJob } from "cron";
import { relative } from "path";
import { fileURLToPath } from "url";

export const registerTasks = async (tasksPath: string, deps: UnpackedDependencies) => {

const taskManager = deps['@sern/scheduler']
for await (const f of Files.readRecursive(tasksPath)) {
let { module } = await Files.importModule<ScheduledTask>(f);

//module.name is assigned by Files.importModule<>
// the id created for the task is unique
const uuid = module.name!+"/"+relative(tasksPath,fileURLToPath(f))
taskManager.schedule(uuid, module.trigger, function(this: CronJob) {
module.execute({
deps,
id: uuid,
lastTimeExecution: this.lastExecution,
nextTimeExecution: this.nextDate().toJSDate()
})
}, module.timezone)
const uuid = module.name+"/"+relative(tasksPath,fileURLToPath(f))
taskManager.schedule(uuid, module, deps)
}
}
4 changes: 2 additions & 2 deletions src/types/core-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export interface SernSubCommandGroupData extends BaseApplicationCommandOptionsDa
}


interface ScheduledTaskContext {
export interface ScheduledTaskContext {
/**
* An object of dependencies configured in `makeDependencies`
*/
Expand All @@ -243,10 +243,10 @@ interface ScheduledTaskContext {
nextTimeExecution: Date | null;
}


export interface ScheduledTask {
name?: string;
trigger: string | Date;
description?: string;
timezone?: string;
execute(tasks: ScheduledTaskContext): Awaitable<void>
}
Expand Down

0 comments on commit 2014e0e

Please sign in to comment.