File size: 2,922 Bytes
f9e1174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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 };