0

所以我刚刚学会了如何使用 node.js 和议程作为我正在开发的后端的调度程序。我现在有一个小问题,我的工作通常需要一些时间才能完成,但议程一旦开始就立即给我一个完成的工作,另一件事是我如何将错误提交到议程上以在那里处理它们。

var reader = require('rss-to-json');
var mongo = require('mongodb').MongoClient;

var feedUrl = "Some URL to an RSS feed";
var url_DB = "mongodb://localhost:27017/";

var db_env = "Dev";

const loadFeed = url => {
  reader.load(url, (err, res) => {
    if (err) throw new Error(err);
    updateEvents(res);
  });
};

const updateEvents = (data) => {
  mongo.connect(url_DB, { useNewUrlParser: true }, (err, db) => {
    if (err) throw new Error(err);
    var dbo = db.db(db_env);
    var counter = 0;
    data.items.forEach(e => {
      var query = { title: e.title };
      dbo.collection("feeds").findOne(query, (err, res) => {
        if (err) throw new Error(err);
        counter++;
        if (res == null) {
          insertElement(e, dbo);
        } else if (res.description != e.description) {
          updateElement(e, dbo);
        }
        if (counter >= data.items.length) db.close();
      });
    });
  });
};

const updateElement = (data, dbo) => {
        var query = { title: data.title };
        dbo.collection("feeds").updateOne(query, { $set: data }, (err, res) => {
            if (err) throw new Error(err);
            // console.log(data.title + " updated");
        });
};

const insertElement = (data, dbo) => {
    dbo.collection("feeds").insertOne(data, (err, res) => {
        if (err) throw new Error(err);
        // console.log(data.title + " inserted");
    });
};


exports.run = () => {
  loadFeed(feedUrl);
};

这是我的一项工作的代码。

希望能帮助谁获得议程以识别脚本的运行时以及如何传递错误。

议程代码

var agenda = require('agenda');
var events = require('../datacollectors/events/index');
var plan = require('../datacollectors/plan/index');
var lectures = require('../datacollectors/lectures/index');
var feed = require('../datacollectors/newsfeed/index');
var course = require('../datacollectors/courses/index');

var url_DB = "mongodb://localhost:27017/agenda";

var agent = new agenda({db: {address: url_DB}});

//other jobs

agent.define('Update Feed', async (job, done) => {
  try {
    await feed.main();
    done();
  } catch (err) {
    done(err);
  }
});

exports.get = () => {
  return agent;
};

exports.run = async () => {
  await agent.start();
  await agent.every('15 minutes', ['Update StuV-Events', 'Update Feed']);
  await agent.every('1 hour', 'Update Vorlesungen');
  await agent.every('1 day', ['Update Mensaplan', 'Update Kurse']);
};

问候,

支持者

4

0 回答 0