Files
zhub/zsub/ztimer.go
lxy 320a94af2d 新增:zconn.appendTo 方法,调整代码风格
git-svn-id: svn://47.119.165.148/zhub@65 e63fbceb-bcc3-4977-ac22-735b83d8d0f4
2021-01-10 18:02:12 +00:00

61 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package zsub
import (
"github.com/robfig/cron"
"strings"
)
type ZTimer struct {
conns []*ZConn
expr string
topic string
cron *cron.Cron
}
/*
1、["timer", topic, expr]
2、["timer", topic]
*/
func (s *ZSub) timer(rcmd []string, c *ZConn) {
s.Lock()
defer s.Unlock()
timer := s.timers[rcmd[1]]
if timer == nil {
timer = &ZTimer{
conns: []*ZConn{},
topic: rcmd[1],
}
s.timers[rcmd[1]] = timer
}
timer.conns = c.appendTo(timer.conns)
// todo: when timer.expr changed send message to all the timers subscribe
if len(rcmd) == 3 && !strings.EqualFold(timer.expr, rcmd[2]) {
timer.expr = rcmd[2]
if timer.cron != nil {
timer.cron.Stop()
}
timer.cron = func() *cron.Cron {
c := cron.New()
c.AddFunc(timer.expr, func() {
//fmt.Println(time.Now().Second())
for _, conn := range timer.conns {
send(conn.conn, "timer", timer.topic)
}
})
go c.Run()
return c
}()
}
s.timers[rcmd[1]] = timer
}
func (t *ZTimer) close(c *ZConn) {
for i, item := range t.conns {
if item.conn == c.conn {
t.conns = append(t.conns[:i], t.conns[i+1:]...)
}
}
}