Remove five second ticker and replace with sleep

This prevents the process from waking up every five seconds even when
there are no requests
This commit is contained in:
Balakrishnan Balasubramanian 2022-12-27 19:39:41 -05:00
parent 99994c6722
commit 0354436ab6
3 changed files with 21 additions and 18 deletions

View File

@ -34,29 +34,32 @@ func NewGList(chatID int, items ...string) *GList {
return &g
}
var reqs chan *GList
var PersistReqC chan<- *GList
func DoPersist() {
reqs = make(chan *GList, 50)
func startPersistenceGoR() {
reqs := make(chan *GList, 50)
PersistReqC = reqs
go func() {
for range time.Tick(5 * time.Second) {
lists := map[*GList]struct{}{}
loop:
for {
select {
case g := <-reqs:
lists[g] = struct{}{}
default:
break loop
}
lists := map[*GList]struct{}{}
for g := range reqs {
lists[g] = struct{}{}
time.Sleep(5 * time.Second)
for len(reqs) > 0 {
g := <-reqs
lists[g] = struct{}{}
}
for g := range lists {
g.persist()
}
lists = make(map[*GList]struct{}, len(lists))
}
}()
}
func init() {
startPersistenceGoR()
}
func (g *GList) persist() {
g.Mutex.Lock()
defer g.Mutex.Unlock()
@ -80,14 +83,14 @@ outer:
}
g.Items = append(g.Items, Entry{text, false})
}
reqs <- g
PersistReqC <- g
}
func (g *GList) Toggle(text string) error {
for i, item := range g.Items {
if item.Text == text {
g.Items[i].Checked = !g.Items[i].Checked
reqs <- g
PersistReqC <- g
return nil
}
}
@ -102,7 +105,7 @@ func (g *GList) ClearChecked() {
}
}
g.Items = remaining
reqs <- g
PersistReqC <- g
}
type button struct {

View File

@ -23,7 +23,8 @@ func TestGList(t *testing.T) {
func TestSplit(t *testing.T) {
g := GList{}
reqs = make(chan *GList, 50)
//This resets the channel, so test does not try to persist
PersistReqC = make(chan *GList, 50)
g.Add("foo")
g.Add("bar\nfoo\nblah")
g.Add("foo")

View File

@ -50,7 +50,6 @@ func main() {
}()
glist.DataPath = dataPath
glist.DoPersist()
log.Printf("Grocery List bot starting with datapath:%s, port:%d\n", dataPath, port)