aboutsummaryrefslogtreecommitdiff
path: root/common/timer.go
diff options
context:
space:
mode:
Diffstat (limited to 'common/timer.go')
-rw-r--r--common/timer.go28
1 files changed, 28 insertions, 0 deletions
diff --git a/common/timer.go b/common/timer.go
new file mode 100644
index 0000000..553a8fd
--- /dev/null
+++ b/common/timer.go
@@ -0,0 +1,28 @@
+package common
+
+import (
+ "context"
+ "time"
+
+ "github.com/nyttikord/gokord/bot"
+)
+
+func NewTimer(ctx context.Context, d time.Duration, fn func(context.Context, context.CancelFunc)) context.CancelFunc {
+ ctx, cancel := context.WithCancel(ctx)
+ logger := bot.Logger(ctx).With("module", "timer")
+ ctx = bot.SetLogger(ctx, logger)
+ go func(ctx context.Context, d time.Duration) {
+ ticker := time.NewTicker(d)
+ fn(ctx, cancel)
+ for {
+ select {
+ case <-ticker.C:
+ fn(ctx, cancel)
+ case <-ctx.Done():
+ ticker.Stop()
+ return
+ }
+ }
+ }(ctx, d)
+ return cancel
+}