如何让我的NodeJS应用程序永远在一个循环中运行 [英] How to have my NodeJS app run in a loop for ever

查看:1183
本文介绍了如何让我的NodeJS应用程序永远在一个循环中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个NodeJS应用程序,它调用一个API,并在特定的时间在工作日发布到一个端点。

I have written a NodeJS app that calls an API and posts to an endpoint only on weekdays at a specific time.

我可以设置一个cron作业来运行应用程序在指定的时间,但我宁愿运行它与 node index.js 并让它运行不断,什么都不做,直到它是正确的日子,然后回去睡觉直到第二天。

I could setup a cron job to run the app at the specified time but I'd prefer to run it with node index.js and have it run constantly, doing nothing until it's the right day and time and then going back to "sleep" until the following day.

我该如何实现?我尝试一个循环:

How do I achieve that? I tried with a while loop:

while (true) {
  myApp.run();
}

显然没有太好。

正确的方法是什么?我应该重写我的模块以使用事件,这样当我的时间发出一个,并且有一个听众对它做出反应?

What's the right way to do it? Should I rewrite my modules to use events, so that I emit one when it's time and there is a listener that reacts to it?

- 编辑:为了更具体,我希望它以类似的方式运行到具有网络服务器的应用程序。当您启动应用程序时,它正在运行并等待连接;当请求&连接结束,它保持运行等待更多的请求&连接。

--edit: To be more specific, I would like it to run in a similar way to an app that has a webserver in it. When you start the app, it's running and waiting for connections; it doesn't exit when the request & connection end, it stays running waiting for more requests & connections.

- 编辑2:我宁愿不使用cron的原因是因为可以在 app.json 应用程序解析的文件。我宁愿避免混淆 cron ,只需通过编辑 config.json 文件更改日程。

--edit 2: The reason I'd rather not use a cron is because the days and time to run on are configurable in a config.json file that the app parses. I'd rather avoid messing with cron and just change the schedule by editing the config.json file.

- 编辑3:我想自己编写代码,不使用模块。我的大脑总是在试图编写一个可以永远运行的应用程序时感到伤心,我想了解它是如何完成的,而不是使用模块。

--edit 3: I'd like to code this myself and not use a module. My brain always hurts when trying to write an app that would run forever and I'd like to understand how it's done rather than using a module.

- 编辑4:这是我最后使用的:

--edit 4: Here is what I ended up using:

function doStuff() {
  // code to run
};

function run() {
  setInterval(doStuff, 30000);
};

run();


推荐答案

你可以随时使用一个简单的 setInterval < a>:

well you could always use a simple setInterval:

 function execute(){
   //code to execute

 }


 setInterval(execute,<calculate time interval in milliseconds you want to execute after>);

这是一个非常裸体的基本方法。希望这有帮助。

this is a very bare-bones basic way to do it. Hope this helps.

这篇关于如何让我的NodeJS应用程序永远在一个循环中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆