Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自动重启服务的定时任务脚本 #129

Open
xiaotiandada opened this issue Feb 21, 2023 · 0 comments
Open

自动重启服务的定时任务脚本 #129

xiaotiandada opened this issue Feb 21, 2023 · 0 comments

Comments

@xiaotiandada
Copy link
Owner

这里提供一个 Node.js 实现的自动重启服务的定时任务脚本。脚本基于 cron 模块进行定时任务的调度,每隔一定时间检查服务的运行状态,如果服务停止运行,则自动重启服务。

const { exec } = require('child_process');
const cron = require('cron');

// 定义服务的启动命令
const startCommand = 'npm start';

// 定义检查服务状态的命令
const checkStatusCommand = 'systemctl is-active my-service';

// 创建定时任务
const task = new cron.CronJob('*/5 * * * *', () => {
  // 每隔 5 分钟执行一次任务

  exec(checkStatusCommand, (err, stdout) => {
    if (err) {
      console.error(err);
      return;
    }

    if (stdout.trim() !== 'active') {
      console.log(`[${new Date().toLocaleString()}] Service is not running, starting service...`);
      exec(startCommand, (err) => {
        if (err) {
          console.error(err);
        }
      });
    }
  });
});

// 启动定时任务
task.start();

console.log('Auto restart task has been started.');

注意,上述代码中的 startCommand 和 checkStatusCommand 可能需要根据实际情况进行修改。如果你的服务是通过 systemd 管理的,那么 checkStatusCommand 可以直接使用 systemctl is-active 命令进行检查。如果你的服务是通过 pm2 管理的,那么 checkStatusCommand 可以使用 pm2 describe 命令进行检查。

另外,脚本中的定时任务是每隔 5 分钟检查一次服务的运行状态,你可以根据实际需求进行调整。

#!/bin/bash

# Set the interval between checks in seconds
interval=300

# Set the name of the process to check and restart
process_name="your_process_name"

while true; do
    # Get the status of the process using pm2 describe
    status=$(pm2 describe $process_name | grep status | awk '{print $2}')

    # If the process is stopped or errored, restart it
    if [[ "$status" == "stopped" ]] || [[ "$status" == "errored" ]]; then
        echo "Restarting $process_name"
        pm2 start $process_name
    fi

    # Wait for the next interval
    sleep $interval
done

将 your_process_name 替换为实际的进程名称,将 interval 替换为检查间隔时间(以秒为单位)。运行此脚本将会每隔一定时间检查进程状态并自动重启,确保进程始终处于运行状态。

const { exec } = require('child_process');

// 设置重启的应用名称
const appName = 'your-app-name';

// 设置检查应用状态的间隔时间,单位为毫秒
const interval = 30000;

// 设置应用崩溃后的最大重启次数
const maxRetries = 3;

let retries = 0;

console.log(`Starting monitor for ${appName}...`);

// 启动定时任务
setInterval(() => {
  exec(`pm2 describe ${appName}`, (err, stdout, stderr) => {
    if (err || stderr) {
      console.error(`Failed to describe ${appName}: ${err || stderr}`);
      retries++;
      if (retries > maxRetries) {
        console.error(`Max retries reached, stopping monitor for ${appName}.`);
        process.exit(1);
      }
      console.log(`Retrying in ${interval / 1000} seconds...`);
      return;
    }
    const description = JSON.parse(stdout)[0];
    if (description.pm2_env.status !== 'online') {
      console.error(`${appName} is not online, current status is ${description.pm2_env.status}. Restarting...`);
      exec(`pm2 restart ${appName}`, (err, stdout, stderr) => {
        if (err || stderr) {
          console.error(`Failed to restart ${appName}: ${err || stderr}`);
        } else {
          console.log(`${appName} has been restarted.`);
          retries = 0;
        }
      });
    } else {
      console.log(`${appName} is online.`);
    }
  });
}, interval);

你需要将 your-app-name 替换为你的应用名称,并根据需要修改检查间隔时间和最大重试次数。运行该脚本后,它将每隔一定时间检查一次应用状态,并在应用崩溃后尝试重启。

-- chatGPT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant