是否可以在node.js中为多个独立任务创建多个计时器?

Is it possible to create multiple timers in node.js for multiple independent tasks?

本文关键字:任务 独立 创建 计时器 node js 是否      更新时间:2023-09-26

我有一个node.js服务器接受来自网页的请求。在收到"START"请求后,我希望能够生成一个计时器,每n秒在后台执行一个任务。这可行吗?有什么好的例子呢?一个简单的伪代码如下:

app.get("myindependenttasks/starttask/:userid"){
   //start a simple timer to handle to userid
   //continue to run the timers endlessly while 
   //while this call returns a "Task running" status
   //to the user.
   //Other users should be able to run their own tasks.
}

如果用户请求的数量在1000个左右,是否有任何缺点?

您可以使用setInterval (http://nodejs.org/api/timers.html),但我会犹豫是否要为1000个这样做。

相反,您应该运行一个setInterval,并在此任务中为所有连接的用户运行任务。

因此,当用户点击"myindependenttasks/starttask/:userid"时,它会被添加到要处理的用户列表中,并且在您的周期性任务中,您将逐个浏览该列表