From a24f7f33e83431c53fa7a80f813a8fc130634716 Mon Sep 17 00:00:00 2001 From: PxlLoewe <72106766+PxlLoewe@users.noreply.github.com> Date: Mon, 2 Jun 2025 13:48:08 -0700 Subject: [PATCH] added chronjob to clean up missions --- apps/dispatch-server/index.ts | 1 + apps/dispatch-server/modules/chron.ts | 51 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/apps/dispatch-server/index.ts b/apps/dispatch-server/index.ts index 184746de..94253b00 100644 --- a/apps/dispatch-server/index.ts +++ b/apps/dispatch-server/index.ts @@ -13,6 +13,7 @@ import { handleConnectDesktop } from "socket-events/connect-desktop"; import cookieParser from "cookie-parser"; import cors from "cors"; import { authMiddleware } from "modules/expressMiddleware"; +import "modules/chron"; const app = express(); const server = createServer(app); diff --git a/apps/dispatch-server/modules/chron.ts b/apps/dispatch-server/modules/chron.ts index e69de29b..1dbbbb8a 100644 --- a/apps/dispatch-server/modules/chron.ts +++ b/apps/dispatch-server/modules/chron.ts @@ -0,0 +1,51 @@ +import { MissionLog, prisma } from "@repo/db"; +import chron from "cron"; + +const removeClosedMissions = async () => { + const oldMissions = await prisma.mission.findMany({ + where: { + state: "running", + }, + }); + oldMissions.forEach(async (mission) => { + const lastAlert = (mission.missionLog as unknown as MissionLog[]).find((l) => { + return l.type === "alert-log"; + }); + const lastAlertTime = lastAlert ? new Date(lastAlert.timeStamp) : null; + + const now = new Date(); + if (!lastAlertTime) return; + // change State to closed if last alert was more than 120 minutes ago + if (lastAlertTime && now.getTime() - lastAlertTime.getTime() > 120 * 60 * 1000) { + const log: MissionLog = { + type: "completed-log", + auto: true, + timeStamp: new Date().toISOString(), + data: {}, + }; + + await prisma.mission.update({ + where: { + id: mission.id, + }, + data: { + state: "finished", + missionLog: { + push: log as any, + }, + }, + }); + console.log(`Mission ${mission.id} closed due to inactivity.`); + } + }); +}; + +const removeClosedMissionsJob = new chron.CronJob( + "*/5 * * * *", // Every 5 minutes + removeClosedMissions, + null, + true, + "Europe/Berlin", +); + +removeClosedMissionsJob.start();