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

如何为Express Server配置指定日期自动关机与重启

Express 服务器定时启停与崩溃自动重启实现方案

一、定时启停服务

1. 系统级定时任务(推荐)

通过系统自带工具实现跨平台可靠启停,避免Node.js进程停止后无法触发重启的问题。

Linux/macOS(Crontab)

  • 打开crontab编辑界面:crontab -e
  • 添加以下两行任务:
    # 每周六下午3:00停止服务
    0 15 * * 6 pkill -f "nodemon your-server-file.js"
    # 每周一凌晨4:00重启服务(替换为你的项目路径)
    0 4 * * 1 cd /your/project/path && nohup nodemon your-server-file.js > server.log 2>&1 &
    
    说明:pkill -f 精准终止nodemon进程;nohup 让服务后台运行,日志输出到server.log。

Windows(任务计划程序)

  • 创建两个独立任务:
    • 停止服务:触发器设为「每周六下午3点」,操作选「启动程序」,程序填taskkill,参数填/F /IM nodemon.exe(强制终止nodemon进程)。
    • 重启服务:触发器设为「每周一凌晨4点」,操作选「启动程序」,程序填cmd.exe,参数填/c "cd /d C:\your\project\path && nodemon your-server-file.js",勾选「不管用户是否登录都要运行」确保服务后台持续运行。

2. Node.js 内部定时任务(仅适用于停止服务)

若需在代码内实现停止逻辑,可使用node-schedule库,但重启仍需依赖系统定时任务:

  • 安装依赖:npm install node-schedule
  • 在服务器入口文件(如server.js)添加:
    const schedule = require('node-schedule');
    const http = require('http');
    const app = require('./app');
    
    const server = http.createServer(app);
    const PORT = process.env.PORT || 3000;
    
    server.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
    
    // 每周六15:00停止服务
    schedule.scheduleJob('0 0 15 * * 6', () => {
      console.log('Stopping server...');
      server.close(() => {
        console.log('Server stopped');
        process.exit(0);
      });
    });
    

二、nodemon 崩溃自动重启配置

nodemon默认在进程异常崩溃时会自动重启,可通过配置确保无延迟立即重启:

  • 在项目根目录创建nodemon.json配置文件:
    {
      "watch": ["."],
      "ignore": ["node_modules"],
      "delay": 0,
      "exitcrash": true,
      "exec": "node your-server-file.js"
    }
    
  • 修改package.json的启动脚本:
    "scripts": {
      "start": "nodemon"
    }
    
  • 启动服务:npm start

说明:delay: 0 取消重启等待时间,exitcrash: true 强制nodemon在进程崩溃时触发重启,避免特殊异常导致的重启失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:40:39