亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我必須發送數千條提醒,有什么辦法可以避免每分鐘都被提醒?

我必須發送數千條提醒,有什么辦法可以避免每分鐘都被提醒?

Go
慕哥9229398 2023-05-08 15:03:18
我有一個像這樣的結構:type Notifications struct {  Id int  Start *time.Time}notifications := db.GetNotifications()所以現在我需要在時間與當前時間匹配時發送這些通知。1  2018-11-07 09:05:002  2018-11-07 09:05:003  2018-11-07 09:15:00..對我來說,最簡單的方法是使用自動收報機:ticker := time.NewTicker(30 * time.Second)defer ticker.Stop()for {    <-ticker.C    alerts := []Notification    for _, n := range notifications {      if n.Start == // same year, month, day, hour and minute {        alerts = append(alerts, n)       }    }    sendNotifications(alerts)    // TODO mutate the notifications to avoid duplicatation sending}有沒有更有效的方法來做到這一點?匹配時間的最佳方法是什么,我是否必須在我的 if 語句中分別比較 time.Now() 的屬性,如年、月、日、小時和分鐘?即,如果已達到年、月、日、小時和分鐘(忽略秒及以后),則會觸發通知
查看完整描述

1 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

首先,要比較時間值,請使用Time.Equal、Time.Before和time.After方法。比較各個組件根本不可靠:

newYork, _ := time.LoadLocation("America/New_York")


t1 := time.Date(2018, 11, 8, 4, 0, 0, 0, time.UTC)

t2 := t1.In(newYork)


fmt.Printf("%v == %v?\n", t1, t2) // 2018-11-08 04:00:00 +0000 UTC == 2018-11-07 23:00:00 -0500 EST?


fmt.Println(t1.Day() == t2.Day()) // false

fmt.Println(t2.Equal(t1))? ? ? ? ?// true

https://play.golang.org/p/06RcvuI_1Ha


對于調度問題,我會使用time.Timer。

  1. 找出下一個通知

  2. 相應地設置或重置定時器


    1. 計時器觸發后,轉到 1

    2. 如果添加通知,轉到1

    3. 如果通知被刪除,轉到1

這是一個草圖:

package main


import "time"


func main() {

? ? t := time.NewTimer(0)


? ? go func() {

? ? ? ? for range t.C {

? ? ? ? ? ? nextTwo := db.GetNextNotifications(2)


? ? ? ? ? ? // Sanity check

? ? ? ? ? ? if time.Until(nextTwo[0].Start) > 1*time.Second {

? ? ? ? ? ? ? ? // The timer went off early. Perhaps the notification has been

? ? ? ? ? ? ? ? // deleted?

? ? ? ? ? ? ? ? t.Reset(time.Until(nextTwo[0].Start))

? ? ? ? ? ? ? ? continue

? ? ? ? ? ? }


? ? ? ? ? ? go send(nextTwo[0])

? ? ? ? ? ? t.Reset(time.Until(nextTwo[1].Start))

? ? ? ? }

? ? }()


? ? resetTimer(t) // call as required whenever a notification is added or removed

}


func resetTimer(t *time.Timer) {

? ? next := db.GetNextNotification()

? ? t.Reset(time.Until(next.Start))

}


查看完整回答
反對 回復 2023-05-08
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號