在Meteor.js中运行后台任务

时间:2015-03-04 10:28:49

标签: javascript meteor

这是我的情景:

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

因为,目前我对Meteor并不擅长,这就是我要做的事情:

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分钟运行一次的任务?

2 个答案:

答案 0 :(得分:4)

有类似Cron的系统,例如Meteor的percolate:synced-cron。在那里,您可以使用Later.js语法注册作业,类似于从percolate:synced-cron自述文件中获取的此示例:

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;
  }
});

如果您想依赖OS级别的cron作业,您只需在Meteor.js应用程序that you could then access through curl at the chosen time中提供HTTP端点。

答案 1 :(得分:1)

我可以建议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
    })
})

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

相关问题