簡體   English   中英

流星:使用setInterval()每天運行一次函數

[英]Meteor: Using setInterval() To Run Function Once Per Day

我正在嘗試運行一個功能,該功能將搜索某些參數,並且每天僅向用戶發送一次電子郵件。

我發現可以完成許多方法。 似乎setInterval()可以做到這一點。

 setInterval(function () {
    var date = new Date();
    if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
        alert("Surprise!!")
    }
}, 1000)

例如,以上內容每天都會在上午10點觸發。

我還發現有一個運行cron作業的軟件包。 https://github.com/percolatestudio/meteor-synced-cron

看來我可以設定一項日常工作來每天發送電子郵件。 我從未使用過cron作業,因此我認為此刻對我而言這將更加困難。

最后,我也找到了這樣做的方法: 每天一次更改功能

僅具有常規功能。

似乎setTimeout()是完成它的最簡單方法。 但是有什么挫折嗎? 我不想錯過電子郵件,或者不想多次錯過電子郵件用戶。 我的網站正在運行並且還在不斷發展,所以我不願發現困難的方法。

任何幫助表示贊賞。

我認為您必須使用Meteor.setInterval()而不是setInterval()才能使其在服務器上正常工作。 但是,我用這個功能我需要運行每秒 ; 在更長的時間內,任何類型的cron作業包也可以正常工作,例如synced-cron

因此,完成本主題並可能在相同情況下幫助任何人。 這就是我做的。 我添加了軟件包“ percolate:synced-cron”。 然后在服務器端,我創建了一個文件“ cron.js”。 這是我使用的代碼。 為了隱私起見,我刪除了功能的其余部分,但是重要的部分在這里。 parser.text使得選擇時間變得非常容易。 “每5秒”(每5秒執行一次操作)..或(“上午10點”)將每天上午10點采取措施。 請記住,mongo在UTC時間中設置為標准時間,因此您必須進行轉換。

    if (Meteor.isServer) {
  // optionally set the collection's name that synced cron will use
  SyncedCron.config({
    collectionName: 'somethingDifferent'
  });

  SyncedCron.add({
    name: 'Crunch some important numbers for the marketing department',
    schedule: function(parser) {
      // parser is a later.parse object
      // return parser.text('every 5 seconds');

      return parser.text('at 3:00 am');
      // midnight is at 5pm LA time ... 10 am LA time is 3 am UTC
    },
    job: function(intendedAt) {
      var today = new Date();
      var yesterday = new Date()
      var dayBeforeYesterday = new Date()
      yesterday.setDate(today.getDate() - 1)
      dayBeforeYesterday.setDate(today.getDate() - 2)


      var todaysUsers = Meteor.users.find({   createdAt: {    $lt: (yesterday), $gt: dayBeforeYesterday   } }).fetch()
      //rest of function here

      }
    }
  });

  Meteor.startup(function () {
    // code to run on server at startup
    SyncedCron.start();

    // Stop jobs after 15 seconds
    // Meteor.setTimeout(function() { SyncedCron.stop(); }, 7 * 1000);
  });
}

我建議使用諸如percolate:synced-cron之類的軟件包來實現此目的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM