From 3d1be2b5e9b20f6ba13ec71b68c047d94e2c171e Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Wed, 24 Apr 2024 00:33:52 +0800 Subject: [PATCH] refactor: add daily cronjob to clear old monitor data --- src/server/cronjob/index.spec.ts | 16 ++++++++++++++++ src/server/cronjob/index.ts | 32 +++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) create mode 100644 src/server/cronjob/index.spec.ts diff --git a/src/server/cronjob/index.spec.ts b/src/server/cronjob/index.spec.ts new file mode 100644 index 0000000..ca4aebe --- /dev/null +++ b/src/server/cronjob/index.spec.ts @@ -0,0 +1,16 @@ +import { describe, test } from 'vitest'; +import { initCronjob } from '.'; + +describe.runIf(process.env.TEST_CRONJOB)('cronjob', () => { + const { dailyJob } = initCronjob(); + + test( + 'run dailyjob', + async () => { + await dailyJob.trigger(); + }, + { + timeout: 30_000, + } + ); +}); diff --git a/src/server/cronjob/index.ts b/src/server/cronjob/index.ts index b630d22..41cc6d9 100644 --- a/src/server/cronjob/index.ts +++ b/src/server/cronjob/index.ts @@ -11,15 +11,24 @@ type WebsiteEventCountSqlReturn = { export function initCronjob() { const dailyJob = Cron('0 2 * * *', async () => { - logger.info('Start statistics usage'); + logger.info('Start daily cronjob'); - await statdailyUsage(); + try { + await statDailyUsage(); + await clearMonitorDataDaily(); + + logger.info('Daily cronjob completed'); + } catch (err) { + logger.error('Daily cronjob error:', err); + } }); logger.info('Daily job will start at:', dailyJob.nextRun()?.toISOString()); + + return { dailyJob }; } -async function statdailyUsage() { +async function statDailyUsage() { logger.info('Statistics Workspace Daily Usage Start'); const start = dayjs().subtract(1, 'day').startOf('day').toDate(); const end = dayjs().startOf('day').toDate(); @@ -125,3 +134,20 @@ async function statdailyUsage() { logger.info('Statistics Workspace Daily Usage Completed'); } + +/** + * Clear over 2 week data + */ +async function clearMonitorDataDaily() { + const date = dayjs().subtract(2, 'weeks').toDate(); + logger.info('Start clear monitor data before:', date.toISOString()); + const res = await prisma.monitorData.deleteMany({ + where: { + createdAt: { + lte: date, + }, + }, + }); + + logger.info('Clear monitor completed, delete record:', res.count); +}