Skip to content

Commit

Permalink
scheduler ids
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jul 5, 2024
1 parent c252854 commit 210aa41
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 19 deletions.
6 changes: 6 additions & 0 deletions src/core/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
InputCommand,
InputEvent,
Module,
ScheduledTask,
} from '../types/core-modules';
import { partitionPlugins } from './functions'
import type { Awaitable } from '../types/utility';
Expand Down Expand Up @@ -46,3 +47,8 @@ export function discordEvent<T extends keyof ClientEvents>(mod: {
return eventModule({ type: EventType.Discord, ...mod, });
}


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

12 changes: 10 additions & 2 deletions src/core/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@ import { CronJob } from 'cron';
export class TaskScheduler {
private __tasks: Map<string, CronJob> = new Map();

scheduleTask(taskName: string, cronExpression: string, task: () => void): boolean {
scheduleTask(taskName: string, cronExpression: string | Date, task: () => void, tz: string| undefined): boolean {
if (this.__tasks.has(taskName)) {
console.warn("While scheduling a task",
"found another task of same name. Not scheduling",
taskName, "again");
return false;
}
try {
const job = new CronJob(cronExpression, task);
const job = CronJob.from({
cronTime: cronExpression,
onTick: task,
timeZone: tz
});
job.start();
this.__tasks.set(taskName, job);
return true;
} catch (error) {
console.error("While scheduling a task " + error);
return false;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export default async function(dir: string, deps : UnpackedDependencies) {
if(!validType) {
throw Error(`Found ${module.name} at ${module.meta.absPath}, which has incorrect \`type\``);
}
const resultModule = await callInitPlugins(module, deps, true); // FREEZE! no more writing!!

const resultModule = await callInitPlugins(module, deps, true);
// FREEZE! no more writing!!
commands.set(resultModule.meta.id, Object.freeze(resultModule));
sEmitter.emit('module.register', resultPayload('success', resultModule));
}
Expand Down
32 changes: 19 additions & 13 deletions src/handlers/tasks.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
import { TaskScheduler } from "../core/schedule"
import * as Files from '../core/module-loading'
import { UnpackedDependencies } from "../types/utility";
import { ScheduledTask } from "../types/core-modules";
import { CronJob } from "cron";
import { relative } from "path";
import { fileURLToPath } from "url";

interface ScheduledTaskModule {
name?: string;
description?: string;
pattern: string;
execute(deps: UnpackedDependencies, tasks: string[]): any
}

export const registerTasks = async (path: string, deps: UnpackedDependencies) => {
export const registerTasks = async (tasksPath: string, deps: UnpackedDependencies) => {
const taskManager = new TaskScheduler()

for await (const f of Files.readRecursive(path)) {
let { module } = await Files.importModule<ScheduledTaskModule>(f);
for await (const f of Files.readRecursive(tasksPath)) {
let { module } = await Files.importModule<ScheduledTask & { meta: { absPath: string } }>(f);

//module.name is assigned by Files.importModule<>
taskManager.scheduleTask(module.name!, module.pattern, () => {
module.execute(deps, taskManager.tasks())
})
// the id created for the task is unique
const uuid = module.name!+":"+relative(tasksPath,fileURLToPath(f))
taskManager.scheduleTask(uuid, module.pattern, function(this: CronJob) {
module.execute({
deps,
runningTasks: taskManager.tasks(),
lastTimeExecution: this.lastExecution,
nextTimeExecution: this.nextDate().toJSDate()
})
},
module.timezone)
}

}
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export type {
SernOptionsData,
SernSubCommandData,
SernSubCommandGroupData,
SDT
SDT,
ScheduledTask
} from './types/core-modules';

export type {
Expand All @@ -43,6 +44,7 @@ export {
commandModule,
eventModule,
discordEvent,
scheduledTask
} from './core/modules';

export * from './core/presences'
Expand Down
20 changes: 19 additions & 1 deletion src/types/core-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type {
import type { CommandType, EventType } from '../core/structures/enums';
import { Context } from '../core/structures/context'
import { ControlPlugin, InitPlugin, Plugin } from './core-plugin';
import { Awaitable, SernEventsMapping } from './utility';
import { Awaitable, SernEventsMapping, UnpackedDependencies } from './utility';

//state, deps, type (very original)
export type SDT = {
Expand Down Expand Up @@ -222,3 +222,21 @@ export interface SernSubCommandGroupData extends BaseApplicationCommandOptionsDa
type: ApplicationCommandOptionType.SubcommandGroup;
options?: SernSubCommandData[];
}


interface ScheduledTaskContext {
deps: UnpackedDependencies,
lastTimeExecution: Date | null;
runningTasks: string[];
nextTimeExecution: Date | null;
}

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


0 comments on commit 210aa41

Please sign in to comment.