1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-16 03:44:26 +00:00
arikawa/internal/lazytime/timer.go
diamondburned 54cadd2f45 gateway: Refactor for a better concurrent API
This commit refactors the whole package gateway as well as utils/ws
(formerly utils/wsutil) and voice/voicegateway. The new refactor
utilizes a design pattern involving a concurrent loop and an arriving
event channel.

An additional change was made to the way gateway events are typed.
Before, pretty much any type will satisfy a gateway event type, since
the actual type was just interface{}. The new refactor defines a
concrete interface that events can implement:

    type Event interface {
        Op() OpCode
        EventType() EventType
    }

Using this interface, the user can easily add custom gateway events
independently of the library without relying on string maps. This adds a
lot of type safety into the library and makes type-switching on Event
types much more reasonable.

Gateway error callbacks are also almost entirely removed in favor of
custom gateway events. A catch-all can easily be added like this:

    s.AddHandler(func(err error) {
        log.Println("gateway error:, err")
    })
2021-12-14 13:49:34 -08:00

51 lines
837 B
Go

package lazytime
import (
"context"
"time"
)
type Timer struct {
C <-chan time.Time
timer *time.Timer
}
// Reset resets the timer by draining it and resetting the internal channel. If
// this is the first time calling, then a new timer is created.
func (t *Timer) Reset(d time.Duration) {
if t.timer == nil {
t.timer = time.NewTimer(d)
t.C = t.timer.C
return
}
t.Stop()
t.timer.Reset(d)
}
// Stop stops the timer and drains it. If the timer has never been used, then it
// does nothing.
func (t *Timer) Stop() {
if t.timer == nil {
return
}
if !t.timer.Stop() {
select {
case <-t.timer.C:
default:
}
}
}
// Wait blocks until the timer fires or until the context expires.
func (t *Timer) Wait(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}