123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package utils
- import (
- "time"
- )
- var _ Timer = (*timer)(nil)
- type Timer interface {
- i()
- Reset(t time.Duration)
- Stop() bool
- TimeRemaining() time.Duration
- Calc() *time.Timer
- Hang() bool
- Canceled()
- }
- type timer struct {
- timer *time.Timer
- end time.Time
- hang bool
- Cancel chan struct{}
- }
- func NewTimer(t time.Duration) Timer {
- return &timer{time.NewTimer(t), time.Now().Add(t), false, 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)
- if t.Seconds() > 4 {
- s.hang = true
- } else {
- s.hang = false
- }
- }
- 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) Hang() bool {
- return s.hang
- }
- func (s *timer) Canceled() {
- s.Cancel <- struct{}{}
- }
|