fromis_9/backend/services/youtube-scheduler.js

108 lines
2.5 KiB
JavaScript
Raw Normal View History

import cron from "node-cron";
import pool from "../lib/db.js";
import { syncNewVideos } from "./youtube-bot.js";
// 봇별 스케줄러 인스턴스 저장
const schedulers = new Map();
/**
* 개별 스케줄 등록
*/
export function registerBot(botId, intervalMinutes = 2) {
// 기존 스케줄이 있으면 제거
unregisterBot(botId);
// cron 표현식 생성 (1분 시작, X분 간격: 1,3,5,7...)
const cronExpression = `1-59/${intervalMinutes} * * * *`;
const task = cron.schedule(cronExpression, async () => {
console.log(`[Bot ${botId}] 동기화 시작...`);
try {
const result = await syncNewVideos(botId);
console.log(`[Bot ${botId}] 동기화 완료: ${result.addedCount}개 추가`);
} catch (error) {
console.error(`[Bot ${botId}] 동기화 오류:`, error.message);
}
});
schedulers.set(botId, task);
console.log(
`[Bot ${botId}] 스케줄 등록됨 (${intervalMinutes}분 간격, 1분 오프셋)`
);
}
/**
* 개별 스케줄 해제
*/
export function unregisterBot(botId) {
if (schedulers.has(botId)) {
schedulers.get(botId).stop();
schedulers.delete(botId);
console.log(`[Bot ${botId}] 스케줄 해제됨`);
}
}
/**
* 서버 시작 실행 중인 봇들 스케줄 등록
*/
export async function initScheduler() {
try {
const [bots] = await pool.query(
"SELECT id, check_interval FROM bots WHERE status = 'running'"
);
for (const bot of bots) {
registerBot(bot.id, bot.check_interval);
}
console.log(`[Scheduler] ${bots.length}개 봇 스케줄 등록됨`);
} catch (error) {
console.error("[Scheduler] 초기화 오류:", error);
}
}
/**
* 시작
*/
export async function startBot(botId) {
const [bots] = await pool.query("SELECT * FROM bots WHERE id = ?", [botId]);
if (bots.length === 0) {
throw new Error("봇을 찾을 수 없습니다.");
}
const bot = bots[0];
// 스케줄 등록
registerBot(botId, bot.check_interval);
// 상태 업데이트
await pool.query(
"UPDATE bots SET status = 'running', error_message = NULL WHERE id = ?",
[botId]
);
// 즉시 1회 실행
try {
await syncNewVideos(botId);
} catch (error) {
console.error(`[Bot ${botId}] 초기 동기화 오류:`, error.message);
}
}
/**
* 정지
*/
export async function stopBot(botId) {
unregisterBot(botId);
await pool.query("UPDATE bots SET status = 'stopped' WHERE id = ?", [botId]);
}
export default {
initScheduler,
registerBot,
unregisterBot,
startBot,
stopBot,
};