Files
var-monorepo/apps/dispatch-server/modules/chron.ts
2025-06-02 13:48:08 -07:00

52 lines
1.2 KiB
TypeScript

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();