From 68da9f192684a4c5cdd239fa5c26f36f4df815be Mon Sep 17 00:00:00 2001 From: michaelschal <35957947-michaelschal@users.noreply.replit.com> Date: Mon, 1 Sep 2025 20:43:07 +0000 Subject: [PATCH] Improve automatic backup scheduling reliability Replace native setTimeout with node-cron for daily automatic backups at 2:00 AM, improving scheduling robustness and adding timezone support. Replit-Commit-Author: Agent Replit-Commit-Session-Id: db1bcb73-80c1-4bff-8236-4ced2c07f75f Replit-Commit-Checkpoint-Type: full_checkpoint --- server/backupService.ts | 41 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/server/backupService.ts b/server/backupService.ts index b4f2170..f88c2b2 100644 --- a/server/backupService.ts +++ b/server/backupService.ts @@ -4,6 +4,7 @@ import fs from 'fs'; import path from 'path'; import { nanoid } from 'nanoid'; import { eq, desc } from "drizzle-orm"; +import cron from 'node-cron'; import { db } from "./db"; import { databaseBackups } from "@shared/schema"; import type { DatabaseBackup, InsertDatabaseBackup } from "@shared/schema"; @@ -211,35 +212,21 @@ export class BackupService { } private scheduleAutomaticBackup(): void { - // Use native setTimeout instead of node-cron for ESM compatibility - const scheduleNextBackup = () => { - const now = new Date(); - const next2AM = new Date(now); - next2AM.setHours(2, 0, 0, 0); - - // If it's already past 2 AM today, schedule for tomorrow - if (now.getHours() >= 2) { - next2AM.setDate(next2AM.getDate() + 1); + // Use node-cron for reliable scheduling in production + // Schedule daily backup at 2:00 AM (0 2 * * * means: minute=0, hour=2, any day, any month, any weekday) + cron.schedule('0 2 * * *', async () => { + try { + console.log('🔄 Starting automatic backup...'); + await this.createBackup('automatic', 'system'); + console.log('✅ Automatic backup completed'); + } catch (error) { + console.error('❌ Automatic backup failed:', error); } - - const msUntilBackup = next2AM.getTime() - now.getTime(); - - setTimeout(async () => { - try { - console.log('🔄 Starting automatic backup...'); - await this.createBackup('automatic', 'system'); - console.log('✅ Automatic backup completed'); - } catch (error) { - console.error('❌ Automatic backup failed:', error); - } - - // Schedule the next backup (24 hours later) - scheduleNextBackup(); - }, msUntilBackup); - }; + }, { + timezone: "Europe/Paris" // Adjust timezone as needed + }); - scheduleNextBackup(); - console.log('⏰ Automatic backup scheduled for 2:00 AM daily (native timer)'); + console.log('⏰ Automatic backup scheduled for 2:00 AM daily (node-cron)'); } }