queue
Viewing readonly version: 89View latest version
Script
999
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { InArgs, sqlite } from "https://esm.town/v/stevekrouse/sqlite?v=13";
import pTimeout from "p-timeout";
import { parseImportMeta } from "./parseImportMeta";
const { projectName } = parseImportMeta(import.meta.url);
const DB_TABLE_PREFIX = `${projectName}_v1_`;
const makeTableName = (name: string): string => `${DB_TABLE_PREFIX}${name}`;
export async function addTaskToQueue({ name, args }: { name: string; args: any[] }, options?: {
scheduledFor?: Date;
}) {
return (await tasksQuery(`INSERT INTO ${makeTableName("tasks")} (data, scheduled_for) VALUES (?, ?) RETURNING *`, [
JSON.stringify({ args, name }),
(options?.scheduledFor || new Date())?.toISOString(),
])).at(0) as Task;
}
export async function getPendingTasks() {
return await tasksQuery(
`
SELECT * FROM ${makeTableName("tasks")}
WHERE status = 'pending'
AND scheduled_for <= ?
LIMIT 5`,
[new Date().toISOString()],
);
}
export async function getTasks() {
return await tasksQuery(`SELECT * FROM ${makeTableName("tasks")}`);
}
export async function markTaskAsCompleted(id: number, result: any) {
return await tasksQuery(`UPDATE ${makeTableName("tasks")} SET status = 'completed', result = ? WHERE id = ?`, [