Fix issues when trying to create background tasks

pull/1773/head
LASER-Yi 2 years ago
parent af4af41a23
commit c1a26fd9eb
No known key found for this signature in database
GPG Key ID: BB28903D50A1D408

@ -9,7 +9,7 @@ class TaskManager {
private onBeforeUnload(e: BeforeUnloadEvent) {
const message = "Background tasks are still running";
if (this.tasks.some((t) => t.status !== "success")) {
if (this.tasks.some((t) => t.status === "running")) {
e.preventDefault();
e.returnValue = message;
return;
@ -17,22 +17,29 @@ class TaskManager {
delete e["returnValue"];
}
private generateUniqueId(): string {
return "TODO-TODO";
private findTask(ref: Task.TaskRef): Task.Callable | undefined {
return this.tasks.find((t) => t.id === ref.callableId);
}
create<T extends Task.AnyCallable>(fn: T, parameters: Parameters<T>): string {
const newTask = fn as Task.Callable<T>;
create<T extends Task.AnyCallable>(fn: T, parameters: Parameters<T>): symbol {
// Clone this function
const newTask = fn.bind({}) as Task.Callable<T>;
newTask.status = "idle";
newTask.parameters = parameters;
newTask.id = this.generateUniqueId();
newTask.id = Symbol(this.tasks.length);
this.tasks.push(newTask);
return newTask.id;
}
async run(task: Task.Callable) {
async run(taskRef: Task.TaskRef) {
const task = this.findTask(taskRef);
if (task === undefined) {
throw new Error(`Task ${taskRef.name} not found`);
}
if (task.status !== "idle") {
return;
}
@ -44,6 +51,7 @@ class TaskManager {
task.status = "success";
} catch (err) {
task.status = "failure";
throw err;
}
}
}

@ -5,13 +5,13 @@ declare namespace Task {
type AnyCallable = (...args: any[]) => Promise<void>;
export type Callable<T extends AnyCallable = AnyCallable> = T & {
parameters: Parameters<T>;
id: string;
id: symbol;
status: Status;
};
export interface Task {
export interface TaskRef {
name: string;
callableId: string;
callableId: symbol;
description?: string;
}

@ -1,3 +1,4 @@
import { LOG } from "@/utilities/console";
import taskManager from ".";
import { GroupName } from "./group";
@ -5,17 +6,24 @@ export function createTask<T extends Task.AnyCallable>(
name: string,
callable: T,
...parameters: Parameters<T>
): Task.Task {
): Task.TaskRef {
const callableId = taskManager.create(callable, parameters);
LOG("info", "task created", name);
return {
name,
callableId,
};
}
export function dispatchTask(task: Task.Task[], group: GroupName) {
// TODO
export function dispatchTask(tasks: Task.TaskRef[], group: GroupName) {
setTimeout(async () => {
for (const ref of tasks) {
LOG("info", "dispatching task", ref.name);
await taskManager.run(ref);
}
});
}
export function createAndDispatchTask<T extends Task.AnyCallable>(

Loading…
Cancel
Save