Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在NodeJS服务器的后台运行Javascript函数_Javascript_Node.js_Express - Fatal编程技术网

在NodeJS服务器的后台运行Javascript函数

在NodeJS服务器的后台运行Javascript函数,javascript,node.js,express,Javascript,Node.js,Express,我编写了一个函数,定期检查连接的android设备的电池状态,并返回一个数组。如何在服务器启动时运行此功能并使其在向其他页面提供信息的同时持续运行 var minutes = 1, the_interval = minutes * 60 * 500; setInterval(function() { adb.devices().then(function(devices) { var promises = new Array(); for (var i = 0; i <

我编写了一个函数,定期检查连接的android设备的电池状态,并返回一个数组。如何在服务器启动时运行此功能并使其在向其他页面提供信息的同时持续运行

var minutes = 1, the_interval = minutes * 60 * 500;
setInterval(function() {
adb.devices().then(function(devices) {

    var promises = new Array();

    for (var i = 0; i < devices.length; i++){
        promises.push(adb.checkBattery(devices[i]));
    }

    Promise.all(promises).then(function(availableDevices) {
        console.log('Updated:');
        console.log(availableDevices);
        return availableDevices;
    });
});
}, the_interval);

使用express,如果我理解正确,您应该在一定时间间隔内运行它:

var express = require('express');
var app = express();

app.listen(3000, function () {
    yourFunction();
    setInterval(yourFunction, << period in ms >>);
});

function yourFunction()
{
    << your code >>
}
var express=require('express');
var-app=express();
应用程序侦听(3000,函数(){
yourFunction();
setInterval(你的函数,>);
});
函数yourFunction()
{
>
}
如果您想使用您的功能响应web服务器的某些请求,最好使用中间件:

var express = require('express');
var app = express();

app.use(function(req,res) {
    if(condition)
        yourFunction();
})

app.listen(3000, function () {
});

function yourFunction()
{
    << your code >>
}
var express=require('express');
var-app=express();
应用程序使用(功能(请求、恢复){
如果(条件)
yourFunction();
})
应用程序侦听(3000,函数(){
});
函数yourFunction()
{
>
}
根据您可以使用的

server = app.listen(3000, function () {
});

server.on('listening', () => {
   your function()
})

这将放在哪个文件中?app.js?或index.js,任何你想要的名字)如果你已经有了一个应用程序,你最好也显示它的代码。我把它放在app.js里面,它在我的视图文件夹里。当我启动服务器时,它说端口3000已经在使用中。注意:我已经创建了其他页面/路由,可以在启动服务器并转到特定URL时访问这些页面/路由。routes中的这些.js文件与app.js中新创建的函数之间是否存在冲突?看起来您在某个地方有根js文件,它在新app.js之前运行web服务器,这就是为什么使用3000端口的原因。您可以添加到文档的链接(到此信息,而不是到主文档页)?
server = app.listen(3000, function () {
});

server.on('listening', () => {
   your function()
})