我开始学习Node JS已经有几天了。
我的Node应用程序有一个get api,它在触发http://localhost:portnumber/mybooks url时以json格式从MongoDB数据库获取图书信息。
图书模式有四个字段,即标题、作者、类别和价格。现在,我想介绍一个cron作业,它将在每小时的第10分钟和50分钟运行一次。它将检查是否有任何图书价格超过100 (货币在这里不重要),它将从数据库中删除记录(或文档)。意味着它将在上午7:10、7:50运行,然后在下一小时的8:10和8:50运行,依此类推。
我使用应用程序文件夹中的./bin/www命令启动应用程序。但是,我无法确定如何实现这个cron作业服务,以及将此代码放在何处(在哪个文件中),以便在我启动应用程序时使其在上述指定时间运行。
我在这里包含了我到目前为止开发的应用程序的一些代码,让您看一看。目前,它在get rest api上运行良好。
这是app.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// 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;这是index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Book1 = require('../models/mybook.model');
var db = 'mongodb://localhost/mybookdb';
var mongoose = require('mongoose');
mongoose.connect(db);
var conn = mongoose.connection;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/mybooks', function(req, res) {
console.log('Showing all books');
Book1.find({})
.exec(function(err,records){
if(err){
res.send('error has occured');
}else{
console.log(records);
res.json(records);
}
});
});
module.exports = router;和mybook.model为:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title:String,
author:String,
category:String,
price: Number
});
module.exports = mongoose.model('Book', BookSchema);有没有人可以帮我解决如何在哪个文件中实现node-schedule cron来满足我的需求?
发布于 2017-02-03 18:21:11
我能想出怎么做。我是从https://www.npmjs.com/package/node-schedule得到这个想法的。
虽然这不是一个精确的解,但很接近。在这种情况下,cron作业每时每刻都在连续运行,但并未实现删除。cron调度器代码可以放在index.js中,如下所示:
var s = require('node-schedule');
var j = schedule.scheduleJob('* * * * *', function() {
Book1.find({price : {$gt:100}} , function(err, result) {
if(err) {
console.log(err);
}
else {
if(!result) {
console.log("No book found");
} else {
console.log("Found a book with title "+result.title);
}
}
});如果有人可以完成这项工作,确切的要求应该是helpful.Thanks。
https://stackoverflow.com/questions/42018642
复制相似问题