在Meteor.js中运行后台任务

Running background tasks in Meteor.js

本文关键字:运行 后台任务 js Meteor      更新时间:2023-09-26

这是我的场景:

1. Scrape some data every X minutes from example.com
2. Insert it to Mongodb database
3. Subscribe for this data in Meteor App.

因为,目前我不是很擅长流星这就是我要做的:

1. Write scraper script for example.com in Python or PHP.
2. Run script every X minutes with cronjob.
3. Insert it to Mongodb.

是否可以在不使用Python或PHP的情况下完全使用Meteor?如何处理每X分钟运行一次的任务?

有类似Cron的系统,例如filtere:synchronized Cron for Meteor。在那里,您可以使用Later.js语法注册作业,该语法类似于从filtere:synchronized cron readme file:中获取的示例

SyncedCron.add({
  name: 'Crunch some important numbers for the marketing department',
  schedule: function(parser) {
    // parser is a later.parse object
    return parser.text('every 2 hours');
  }, 
  job: function() {
    var numbersCrunched = CrushSomeNumbers();
    return numbersCrunched;
  }
});

如果你想依赖操作系统级的cron作业,你可以在Meteor.js应用程序中提供一个HTTP端点,然后在选择的时间通过curl访问。

我可以推荐Steve Jobs,这是我在Meteor中安排后台工作的新软件包。

您可以使用registerreplicateremove动作

// Register the job
Jobs.register({ 
    dataScraper: function (arg) {
        var data = getData()
        if (data) {
            this.replicate({
                in: {
                    minutes: 5
                }
            });
            this.remove(); // or, this.success(data)
        } else {
            this.reschedule({
                in: {
                    minutes: 5
                }
            })
        }
    }
})
// Schedule the job to run on Meteor startup
// `singular` ensures that there is only pending job with the same configuration
Meteor.startup(function () {
    Jobs.run("dataScraper", {
        in: {
            minutes: 5
        }, 
        singular: true
    })
})

根据您的偏好,您可以将结果存储在数据库中,作为作业历史记录的一部分,也可以将其完全删除。