-
Notifications
You must be signed in to change notification settings - Fork 147
/
resend_msg.go
64 lines (55 loc) · 1.29 KB
/
resend_msg.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
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package common
import (
"github.com/pkg/errors"
"time"
)
var (
ErrParam = errors.New("param err")
)
type ResendMsgCtrl struct {
curTimes uint32
maxTimes uint32
interval time.Duration
msg interface{}
sendFunc func(interface{}, uint32)
closeCh chan struct{}
}
func NewResendMsgCtrl(msg interface{}, sendFunc func(interface{}, uint32), interval int64, times uint32) (*ResendMsgCtrl, error) {
if sendFunc == nil || interval <= 0 {
return nil, ErrParam
}
ctrl := &ResendMsgCtrl{
curTimes: 0,
maxTimes: times,
interval: time.Duration(interval) * time.Second,
msg: msg,
sendFunc: sendFunc,
closeCh: make(chan struct{}),
}
go ctrl.running()
return ctrl, nil
}
func (self *ResendMsgCtrl) Close() {
close(self.closeCh)
}
func (self *ResendMsgCtrl) running() {
self.curTimes = 1
self.sendFunc(self.msg, self.curTimes)
timer := time.NewTimer(self.interval)
for {
select {
case <-timer.C:
if self.maxTimes != 0 && self.curTimes == self.maxTimes {
return
}
self.curTimes++
self.sendFunc(self.msg, self.curTimes)
timer.Reset(self.interval)
case <-self.closeCh:
return
}
}
}