aboutsummaryrefslogtreecommitdiff
path: root/common/timer.go
blob: 553a8fdf3c7cc455e89c4898b95a9cbff632de5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
}