定期运行Meteor方法的最佳方式,但不要太频繁

Best way to run a Meteor method regularly, but not too often?

本文关键字:方式 运行 Meteor 方法 最佳      更新时间:2023-09-26

从Meteor方法中获得合理的最新数据而不让它不断运行的最佳、最有效的方法是什么?

我有一个服务器端Meteor方法,必须检查3-4个集合返回正确的值集。

我们在整个应用程序的几个地方使用了这个方法,但是经常运行它似乎真的很昂贵。

方法:

getContactLimit() {
  let currentOrg   = Meteor.user() && Meteor.user().profile && Meteor.user().profile.currentOrg,
      orgData      = Orgs.findOne( { 'domain': currentOrg } ),
      orgStatus    = orgData && orgData.status,
      orgPlan      = orgData && orgData.billing && orgData.billing.plan,
      allPlans     = Meteor.settings.public.plans,
      thisPlan     = _.find( allPlans, function(plan){ return plan.name == orgPlan; } ),
      planContacts = thisPlan && thisPlan.contacts,
      contactCount = Contacts.find({ 'orgId': currentOrg }).count(),
      countObj     = {
        planCount: planContacts,
        orgCount: contactCount
      };
  return countObj;
}

目前我们只是叫它按需,这还不是问题。但是我们将把它添加到整个应用程序中显示通知。

我看到的一种方法是调用在Meteor.setInterval();函数中包装的方法并让它更新会话变量。

我是这样想的:

Meteor.setInterval(function() {
  Meteor.call( 'getContactLimit', function( error, response ) {
    Session.set('contactLimit', response );
  });    
}, 60000 );

另一种可能性是将它嵌入到特定的操作中,这样它只在特定的活动中运行,但这感觉很粗糙。

任何想法?有没有更好的方法来做到这一点?

谢谢!

我将尝试一个自定义发布函数,在其中我将以设置的间隔运行this.changed。请参阅publish (http://docs.meteor.com/api/pubsub.html)文档中的按房间计数示例。您可以使用其中一个cron包来调度时间间隔。

客户端不需要知道这个hack,可以像订阅其他自定义发布一样订阅。