summaryrefslogtreecommitdiff
path: root/lib/nonsap-sync/purchase-group-code/user-code-sync-scheduler.ts
blob: 23d0b5688442f279e0cae881fd31cd66c57a377f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use server';

import * as cron from 'node-cron';
import { syncUserCodes } from './purchase-group-code-sync';

// CRON 스케줄 (기본: 매일 새벽 3시)
const CRON_STRING = process.env.USER_CODE_SYNC_CRON || '0 3 * * *';

// 애플리케이션 기동 시 최초 한 번 실행 여부
const DO_FIRST_RUN = process.env.USER_CODE_SYNC_FIRST_RUN === 'true';

/**
 * 사용자 코드 동기화 스케줄러 시작
 */
export async function startUserCodeSyncScheduler(): Promise<void> {
  console.log('[USER-CODE-SYNC] 사용자 코드 동기화 스케줄러 초기화 중...');

  try {
    // 환경 변수에 따라 실행시 즉시 실행 여부 결정
    if (DO_FIRST_RUN) {
      console.log('[USER-CODE-SYNC] 첫 실행: 사용자 코드 동기화 즉시 시작');
      syncUserCodes().catch((error) => {
        console.error('[USER-CODE-SYNC] 첫 실행 중 오류:', error);
      });
    }

    // CRON JOB 등록
    cron.schedule(CRON_STRING, async () => {
      try {
        console.log('[USER-CODE-SYNC] CRON 실행: 사용자 코드 동기화 시작');
        await syncUserCodes();
      } catch (error) {
        console.error('[USER-CODE-SYNC] 예약된 동기화 실패:', error);
        // 동기화 실패해도 다음 스케줄은 계속 실행
      }
    }, {
      timezone: 'Asia/Seoul'
    });

    console.log(`[USER-CODE-SYNC] ✅ 사용자 코드 동기화 CRON 작업 등록 완료 (${CRON_STRING})`);
    
  } catch (error) {
    console.error('[USER-CODE-SYNC] 스케줄러 초기화 실패:', error);
    throw error;
  }
}