12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- package utils
- import (
- "time"
- )
- var _ Timer = (*timer)(nil)
- type Timer interface {
- i()
- Reset(t time.Duration)
- Stop() bool
- TimeRemaining() time.Duration
- Calc() *time.Timer
- Canceled()
- }
- type timer struct {
- timer *time.Timer
- end time.Time
- Cancel chan struct{}
- }
- func NewTimer(t time.Duration) Timer {
- return &timer{time.NewTimer(t), time.Now().Add(t), make(chan struct{})}
- }
- func (s *timer) i() {}
- func (s *timer) Reset(t time.Duration) {
- if !s.timer.Stop() {
- select {
- case <-s.timer.C:
- default:
- }
- }
- s.timer.Reset(t)
- s.end = time.Now().Add(t)
- }
- func (s *timer) Stop() bool {
- return s.timer.Stop()
- }
- func (s *timer) TimeRemaining() time.Duration {
- return s.end.Sub(time.Now())
- }
- func (s *timer) Calc() *time.Timer {
- return s.timer
- }
- func (s *timer) Canceled() {
- s.Cancel <- struct{}{}
- }
|