-
Notifications
You must be signed in to change notification settings - Fork 10
/
sync_notifications.go
66 lines (59 loc) · 1.73 KB
/
sync_notifications.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"log"
"time"
)
const (
syncSetName = "sync_notifications_set"
syncInterval = time.Duration(time.Minute * 30)
syncJobName = "chainSync"
)
// registerSyncNotification registeres a device for a periodic sync notification.
// the client will get a data message every "syncInterval" and will be responsible
// to execute a sync.
func registerSyncNotification(deviceToken string) error {
_, err := pushWithScore(
syncSetName, deviceToken, time.Now().Add(syncInterval).Unix())
return err
}
// deliverSyncNotifications executes the main loop of runnig over existing registration
// and sending sync messags on time.
func deliverSyncNotifications() {
for {
deviceToken, score, err := popMinScore(syncSetName)
if err != nil {
log.Println("failed to pop next sync notification ", err)
continue
}
fireTime := time.Unix(int64(score), 0)
<-time.After(fireTime.Sub(time.Now()))
go func() {
unreg, err := sendClientSyncMessage(deviceToken)
if err != nil {
log.Println("error in sending sync message:", err)
}
//if this token is still valid, register for the next sync time.
if !unreg {
if err = registerSyncNotification(deviceToken); err != nil {
log.Println("failed to re-regiseter sync notification for token: ", deviceToken)
}
}
}()
}
}
// sendClientSyncMessage is the function that actualy sends the sync message
// to the client. It also returns a value indicates if this token needs to be
// unregistered.
func sendClientSyncMessage(sendToToken string) (bool, error) {
data := map[string]string{
"_job": syncJobName,
}
err := notifyDataMessage(data, sendToToken)
if err != nil {
if isUnregisteredError(err) {
return true, nil
}
return false, err
}
return false, nil
}