【问题标题】:Run a background task periodically in Meteor在 Meteor 中定期运行后台任务
【发布时间】:2018-06-23 19:15:56
【问题描述】:

假设我有一个显示城市及其温度的小型流星应用程序。这些城市保存在数据库中。

我想要一个服务器非阻塞进程,它会定期拉取网页并解析温度,例如每小时一次,以更新数据库中的值。

我假设一旦新值更新,所有连接的用户都会看到更新后的温度,甚至无需刷新页面。

请问作为 Meteor 初学者,我该如何做到这一点。这个过程应该独立于用户,无论页面上是否有用户,它都应该每小时运行一次。

谢谢!

【问题讨论】:

    标签: node.js mongodb meteor background-process


    【解决方案1】:

    使用 percolate:synced-cron 包创建一个 cron 作业。在服务器上运行。可以使用 momentjs 安排它以任何周期运行。

    【讨论】:

      【解决方案2】:

      我个人会使用meteor-job-collection 来执行此操作。我刚刚从我的项目中提取了一些代码,这将为您提供一个很好的起点。只需将此文件包含在您的服务器代码中并将解析代码添加到作业中即可:

      const parse_RATE = 1000 * 60 * 60;
      const parseQueue = JobCollection('parseQueue');
      
      parseQueue.processJobs('parse', { pollInterval: parse_RATE }, function(job, cb) {
      
         // Parse your web page
      
         <add your code here>
      
         // Signal that the job's done
      
         job.done();
      
         // Since .done() will create a new repeating job, we can now delete
         // this old job so that we don't fill up the database with dead ones.
      
         job.remove();
         cb();
      
      });
      
      // Remove any old jobs that were set up when the server was last running
      
      const oldJobs = parseQueue.find();
      oldJobs.forEach((job) => {
         parseQueue.cancelJobs([job._id]);
         parseQueue.removeJobs([job._id]);
      });
      
      // Create a new parse job
      //
      // We parse at 4am every day when the server is the least busy.
      
      parseQueue.startJobServer();
      
      const job = new Job(parseQueue, 'parse', {});
      job.priority('normal')
         .repeat({ schedule: parseQueue.later.parse.recur().every(1).hour() })
         .save();
      

      【讨论】:

        【解决方案3】:

        您也可以使用我的新Steve Jobs 包。对 Meteor 的做事方式非常友好。

        【讨论】:

        • 能否解释一下与 percolate:synced-cron 的主要区别?
        • @Raz 认为 synced-cron 会在您指定的时间间隔内重复运行一个函数。史蒂夫乔布斯更像是在你指定的时间运行一个方法,你可以根据需要排队,随时运行。
        猜你喜欢
        • 2010-10-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 2016-09-05
        相关资源
        最近更新 更多