简体   繁体   English

当 API 端点被命中时运行脚本,并在再次命中时检查该脚本是否正在运行 - Node.js

[英]Run a script when API endpoint is hit, and check if that script is running when hit again - Node.js

I'm working on a node.js API that needs to start/run a time-intensive javaScript file when a certain endpoint is hit.我正在研究一个 node.js API,当某个端点被命中时,它需要启动/运行一个耗时的 javaScript 文件。 I've got this working, but what I'm now looking for is a way to stop the script from running again if it's already running and the endpoint gets hit again.我已经完成了这项工作,但我现在正在寻找一种方法来阻止脚本再次运行,如果它已经在运行并且端点再次被击中。

I tried to use the child_process library, hoping that if the script is being executed as a separate process from the main node.js app, it would be easier to check if the script is already running.我尝试使用 child_process 库,希望如果脚本作为独立于主 node.js 应用程序的进程执行,则更容易检查脚本是否已经在运行。 I thought of using the process exit event for the child process that I created, but this proved to be unhelpful because it would only run once the process was done, but didn't help in checking if it was currently running.我曾想过为我创建的子进程使用进程退出事件,但这被证明是无用的,因为它只会在进程完成后运行,但无助于检查它当前是否正在运行。

I also had considered cron jobs, but there doesn't seem to be a good way to just start a cron job on command without making a time-based schedule.我也考虑过 cron 作业,但似乎没有一个好方法可以在不制定基于时间的计划的情况下根据命令启动 cron 作业。

In another project, I used a database and simply created a new row in a table to indicate whether the script was available to run, currently running, or finished.在另一个项目中,我使用了一个数据库并简单地在表中创建了一个新行来指示脚本是否可以运行、当前正在运行或已完成。 I could definitely do it this way again, but I'm trying to keep this project as light as possible.我绝对可以再次这样做,但我正在努力使这个项目尽可能轻松。

Lastly, I did consider just adding some global state variable that would indicate if the process is running or not, but wasn't sure if that was the best method.最后,我确实考虑过添加一些全局 state 变量来指示进程是否正在运行,但不确定这是否是最好的方法。

So, if anyone either knows a way to check if a child process script is currently running or has a better way of achieving what I'm trying to achieve here, any direction would be helpful.因此,如果有人知道一种方法来检查子进程脚本当前是否正在运行,或者有更好的方法来实现我在这里想要实现的目标,那么任何方向都会有所帮助。

You can use a variable, and it doesn't even have to be global!你可以使用一个变量,它甚至不必是全局的!

class MySingletonProcess {
  constructor() {
    this.isBusy = false;
  }

  async doProcess() {
    console.log("Doing process...");
    // fake async stuff...
    return new Promise((resolve) => {
      setTimeout(() => {
        this.isBusy = false;
        resolve();
      }, 2500);
    });
  }

  spawnProcess() {
    if (this.isBusy) {
      console.log("I'm busy!");
      return;
    } else {
      this.isBusy = true;
      this.doProcess();
    }
  }
}

Try it out on Codepen在 Codepen 上试用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM