nuno hat die Gist bearbeitet 1 month ago. Zu Änderung gehen
1 file changed, 57 insertions
slots.ts(Datei erstellt)
| @@ -0,0 +1,57 @@ | |||
| 1 | + | import cron from "node-cron"; | |
| 2 | + | import { Client } from "discord.js"; | |
| 3 | + | import { cfg } from "./config"; | |
| 4 | + | import { TGSlot } from "../types"; | |
| 5 | + | ||
| 6 | + | type PollCallback = (slot: TGSlot) => Promise<void>; | |
| 7 | + | type CloseCallback = (slot: TGSlot) => Promise<void>; | |
| 8 | + | ||
| 9 | + | let _scheduledTasks: cron.ScheduledTask[] = []; | |
| 10 | + | ||
| 11 | + | export function scheduleSlots( | |
| 12 | + | client: Client, | |
| 13 | + | onPollOpen: PollCallback, | |
| 14 | + | onPollClose: CloseCallback | |
| 15 | + | ): void { | |
| 16 | + | // Clear existing schedules | |
| 17 | + | _scheduledTasks.forEach((t) => t.stop()); | |
| 18 | + | _scheduledTasks = []; | |
| 19 | + | ||
| 20 | + | const tz = process.env.TZ ?? "Etc/GMT-2"; | |
| 21 | + | const slots = cfg("slots").filter((s) => s.active); | |
| 22 | + | ||
| 23 | + | for (const slot of slots) { | |
| 24 | + | // Parse poll open time | |
| 25 | + | const [openHour, openMin] = slot.pollOpens.split(":").map(Number); | |
| 26 | + | ||
| 27 | + | // Schedule poll open | |
| 28 | + | const openTask = cron.schedule( | |
| 29 | + | `${openMin} ${openHour} * * *`, | |
| 30 | + | () => onPollOpen(slot), | |
| 31 | + | { timezone: tz } | |
| 32 | + | ); | |
| 33 | + | _scheduledTasks.push(openTask); | |
| 34 | + | ||
| 35 | + | // Schedule poll close (tgHour + closesAfter minutes) | |
| 36 | + | const closeMinTotal = slot.tgHour * 60 + slot.closesAfter; | |
| 37 | + | const closeHour = Math.floor(closeMinTotal / 60) % 24; | |
| 38 | + | const closeMin = closeMinTotal % 60; | |
| 39 | + | ||
| 40 | + | const closeTask = cron.schedule( | |
| 41 | + | `${closeMin} ${closeHour} * * *`, | |
| 42 | + | () => onPollClose(slot), | |
| 43 | + | { timezone: tz } | |
| 44 | + | ); | |
| 45 | + | _scheduledTasks.push(closeTask); | |
| 46 | + | } | |
| 47 | + | ||
| 48 | + | // Weekly reset — Monday 00:00 | |
| 49 | + | const resetTask = cron.schedule("0 0 * * 1", () => { | |
| 50 | + | const { resetWeek } = require("./wrank"); | |
| 51 | + | resetWeek(); | |
| 52 | + | console.log("W.Rank weekly reset complete."); | |
| 53 | + | }, { timezone: tz }); | |
| 54 | + | _scheduledTasks.push(resetTask); | |
| 55 | + | ||
| 56 | + | console.log(`Scheduled ${slots.length} slot(s).`); | |
| 57 | + | } | |
Neuer
Älter