GoWeb/internal/scheduler.go

72 lines
1.6 KiB
Go
Raw Normal View History

2023-04-04 19:37:23 +00:00
package app
2023-04-06 14:55:56 +00:00
import (
"sync"
"time"
)
2023-04-04 19:37:23 +00:00
type Scheduled struct {
2024-07-02 02:19:48 +00:00
EveryReboot []func(app *Deps)
EverySecond []func(app *Deps)
EveryMinute []func(app *Deps)
EveryHour []func(app *Deps)
EveryDay []func(app *Deps)
EveryWeek []func(app *Deps)
EveryMonth []func(app *Deps)
EveryYear []func(app *Deps)
2023-04-04 19:37:23 +00:00
}
type Task struct {
2024-07-02 02:19:48 +00:00
Funcs []func(app *Deps)
2023-12-19 22:41:31 +00:00
Interval time.Duration
2023-04-04 19:37:23 +00:00
}
2024-07-02 02:19:48 +00:00
func RunScheduledTasks(app *Deps, poolSize int, stop <-chan struct{}) {
2023-04-04 19:37:23 +00:00
for _, f := range app.ScheduledTasks.EveryReboot {
f(app)
}
tasks := []Task{
2023-12-19 22:41:31 +00:00
{Funcs: app.ScheduledTasks.EverySecond, Interval: time.Second},
{Funcs: app.ScheduledTasks.EveryMinute, Interval: time.Minute},
{Funcs: app.ScheduledTasks.EveryHour, Interval: time.Hour},
{Funcs: app.ScheduledTasks.EveryDay, Interval: 24 * time.Hour},
{Funcs: app.ScheduledTasks.EveryWeek, Interval: 7 * 24 * time.Hour},
{Funcs: app.ScheduledTasks.EveryMonth, Interval: 30 * 24 * time.Hour},
{Funcs: app.ScheduledTasks.EveryYear, Interval: 365 * 24 * time.Hour},
2023-04-04 19:37:23 +00:00
}
2023-04-06 14:55:56 +00:00
var wg sync.WaitGroup
2023-04-04 19:37:23 +00:00
runners := make([]chan bool, len(tasks))
for i, task := range tasks {
runner := make(chan bool, poolSize)
runners[i] = runner
2023-04-06 14:55:56 +00:00
wg.Add(1)
2023-04-04 19:37:23 +00:00
go func(task Task, runner chan bool) {
2023-04-06 14:55:56 +00:00
defer wg.Done()
2023-04-04 19:37:23 +00:00
ticker := time.NewTicker(task.Interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for _, f := range task.Funcs {
runner <- true
2024-07-02 02:19:48 +00:00
go func(f func(app *Deps)) {
2023-04-04 19:37:23 +00:00
defer func() { <-runner }()
f(app)
}(f)
}
case <-stop:
return
}
}
}(task, runner)
}
2023-04-06 14:55:56 +00:00
wg.Wait()
2023-04-04 19:37:23 +00:00
for _, runner := range runners {
close(runner)
}
}