import config from './config.js'; import { fileURLToPath } from 'url'; import path from 'path'; import { checkCookieFile, getHumanReadableTimestamp, log, logError } from './utils/common-utils.js'; import { createBrowserSession, navigateToWebIDE, executeCommandFlow } from './utils/webide-utils.js'; // 执行单次命令的函数 async function executeCommandOnce(page) { log(`[${getHumanReadableTimestamp()}] 开始执行命令...`); return executeCommandFlow(page, 'scheduler'); } // 主调度器函数 async function startScheduler() { // 检查cookie文件是否存在 if (!checkCookieFile(config.cookieFile)) { return; } log(`[${getHumanReadableTimestamp()}] 启动调度器...`); const intervalSeconds = Math.round(config.schedulerInterval / 1000); log(`调度器将每${intervalSeconds}秒执行一次命令以防止编辑器休眠`); let browser; try { // 创建浏览器会话 const { browser: browserInstance, page } = await createBrowserSession(config.cookieFile); browser = browserInstance; // 导航到WebIDE页面 await navigateToWebIDE(page); // 立即执行一次命令 await executeCommandOnce(page); // 设置定时器,按配置的时间间隔执行 const intervalId = setInterval(async () => { try { // 重新导航到页面以确保页面活跃 log(`[${getHumanReadableTimestamp()}] 重新导航到WebIDE页面...`); await navigateToWebIDE(page); // 执行命令 await executeCommandOnce(page); } catch (error) { logError(`[${getHumanReadableTimestamp()}] 定时任务执行失败:`, error); } }, config.schedulerInterval); log(`[${getHumanReadableTimestamp()}] 调度器已启动,将每${intervalSeconds}秒执行一次命令`); log('按 Ctrl+C 停止调度器'); // 监听进程退出信号 process.on('SIGINT', async () => { log(`\n[${getHumanReadableTimestamp()}] 收到停止信号,正在关闭调度器...`); clearInterval(intervalId); if (browser) { await browser.close(); } log('调度器已停止,浏览器已关闭'); process.exit(0); }); // 保持进程运行 process.on('SIGTERM', async () => { log(`\n[${getHumanReadableTimestamp()}] 收到终止信号,正在关闭调度器...`); clearInterval(intervalId); if (browser) { await browser.close(); } log('调度器已停止,浏览器已关闭'); process.exit(0); }); } catch (error) { logError(`[${getHumanReadableTimestamp()}] 调度器启动失败:`, error); if (browser) { await browser.close(); } } } // 运行调度器 const __filename = fileURLToPath(import.meta.url); const scriptPath = path.resolve(process.argv[1]); if (path.resolve(__filename) === scriptPath) { startScheduler().catch(console.error); } export { startScheduler };