0
我寫了一個函數,定期檢查連接的Android設備的電池狀態並返回一個數組。如何在服務器啓動時運行此功能,並在向其他頁面提供信息的同時不斷運行它?在NodeJS服務器的後臺運行Javascript功能
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);
這是我的app.js文件,當我打開一個新項目時自動創建。我爲我創建的各種路線添加了app.use。使用快遞
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var adb = require('./adb.js');
var index = require('./routes/index');
var users = require('./routes/users');
var devices = require('./routes/devices');
var openBrowser = require('./routes/openBrowser');
var closeBrowser = require('./routes/closeBrowser');
var openApp = require('./routes/openApp');
var closeApp = require('./routes/closeApp');
var install = require('./routes/install');
var uninstall = require('./routes/uninstall');
var pull = require('./routes/pull');
var push = require('./routes/push');
var battery = require('./routes/battery');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/devices', devices);
app.use('/openBrowser', openBrowser);
app.use('/openApp', openApp);
app.use('/closeApp', closeApp);
app.use('/install', install);
app.use('/closeBrowser', closeBrowser);
app.use('/uninstall', uninstall);
app.use('/pull', pull);
app.use('/push', push);
app.use('/battery', battery);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
這將被放置在哪個文件? app.js? – rrain
或index.js,你想要的任何名字) –
如果你已經有一個應用程序已經make,你最好也顯示它的代碼。 –