-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
45ecc1a
commit 6460348
Showing
6 changed files
with
91 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package base | ||
|
||
import ( | ||
"context" | ||
"time" | ||
) | ||
|
||
// Ticker | ||
type Ticker struct { | ||
ticker *time.Timer | ||
ctx context.Context | ||
f func() | ||
reset chan struct{} | ||
} | ||
|
||
// NewTicker return a ticker. | ||
func NewTicker(ctx context.Context, interval time.Duration, f func()) *Ticker { | ||
if interval <= 0 { | ||
panic("invalid interval") | ||
} | ||
|
||
t := &Ticker{ | ||
ticker: time.NewTimer(interval), | ||
ctx: ctx, | ||
f: f, | ||
reset: make(chan struct{}), | ||
} | ||
|
||
go func() { | ||
for { | ||
select { | ||
case <-t.ticker.C: | ||
f() | ||
|
||
case <-t.reset: | ||
t.ticker.Reset(interval) | ||
|
||
case <-ctx.Done(): | ||
return | ||
} | ||
} | ||
}() | ||
|
||
return t | ||
} | ||
|
||
func (t *Ticker) ForceFunc() error { | ||
select { | ||
case <-t.ctx.Done(): | ||
return ErrDatabaseClosed | ||
|
||
default: | ||
t.f() | ||
return nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters