aboutsummaryrefslogtreecommitdiffstats
path: root/event.go
blob: 6235ba40e2d1e921b2870e1c7b51adbf0530442e (plain) (blame)
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
package main

import (
	"sync/atomic"
	"time"
)

type Event struct {
	guard    int32
	next     time.Time
	interval time.Duration
	C        chan struct{}
}

func newEvent(interval time.Duration) *Event {
	return &Event{
		guard:    0,
		next:     time.Now(),
		interval: interval,
		C:        make(chan struct{}, 1),
	}
}

func (e *Event) Clear() {
	select {
	case <-e.C:
	default:
	}
}

func (e *Event) Fire() {
	if e == nil || atomic.SwapInt32(&e.guard, 1) != 0 {
		return
	}
	if now := time.Now(); now.After(e.next) {
		select {
		case e.C <- struct{}{}:
		default:
		}
		e.next = now.Add(e.interval)
	}
	atomic.StoreInt32(&e.guard, 0)
}