You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PM2定时启动和停止服务?

如何用PM2实现服务的定时启动与停止

可以实现,但PM2本身没有提供直接的cron_start或cron_stop配置项,需要结合系统cron任务或自定义调度脚本来完成,以下是两种可行方案:

方案一:系统cron直接调用PM2命令

这是最直接的方式,通过系统的cron定时执行PM2的启动/停止命令:

  1. 编辑当前用户的cron任务:
    crontab -e
    
  2. 添加定时启动和停止规则:
    # 每天17:00启动search-api服务
    0 17 * * * pm2 start ecosystem.config.js --only search-api
    # 每天21:00停止search-api服务
    0 21 * * * pm2 stop search-api
    
  3. 保存退出后,cron会自动加载新任务

注意:如果系统找不到pm2命令,需要替换为PM2的绝对路径(比如/usr/local/bin/pm2),可以用which pm2命令查看路径。

方案二:PM2配合自定义调度脚本

如果想把调度逻辑统一在PM2配置中管理,可以写一个Node.js调度脚本,通过node-schedule库控制服务启停:

  1. 安装依赖:
    npm install node-schedule
    
  2. 编写调度脚本scheduler.js:
    const { exec } = require('child_process');
    const schedule = require('node-schedule');
    
    // 每天17:00启动服务
    schedule.scheduleJob('0 17 * * *', () => {
      exec('pm2 start search-api', (err) => {
        if (err) console.error('启动服务失败:', err);
      });
    });
    
    // 每天21:00停止服务
    schedule.scheduleJob('0 21 * * *', () => {
      exec('pm2 stop search-api', (err) => {
        if (err) console.error('停止服务失败:', err);
      });
    });
    
  3. 在PM2的生态配置文件ecosystem.config.js中添加调度脚本和目标服务:
    module.exports = {
      apps: [
        {
          name: 'service-scheduler',
          script: './scheduler.js',
          interpreter: 'node',
          autorestart: true, // 调度脚本自身保持运行
        },
        {
          name: 'search-api',
          script: './api.js',
          autorestart: false, // 禁止自动重启,由调度脚本控制
        }
      ]
    };
    
  4. 启动所有服务:
    pm2 start ecosystem.config.js
    

注意事项

  • 确保PM2开机自启:执行pm2 startup命令配置,避免系统重启后调度失效
  • 系统cron任务注意用户权限:如果服务是用普通用户启动的,要确保编辑的是对应用户的cron,而非root用户的
  • 测试规则:可以修改cron时间为当前时间后1分钟,验证启停是否正常

内容的提问来源于stack exchange,提问作者SVill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 21:34:52