GoWeb/app/schedule.go

76 lines
1.7 KiB
Go
Raw Permalink 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 {
EveryReboot []func(app *App)
EverySecond []func(app *App)
EveryMinute []func(app *App)
EveryHour []func(app *App)
EveryDay []func(app *App)
EveryWeek []func(app *App)
EveryMonth []func(app *App)
EveryYear []func(app *App)
}
type Task struct {
Interval time.Duration
Funcs []func(app *App)
}
func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
// Run every time the server starts
for _, f := range app.ScheduledTasks.EveryReboot {
f(app)
}
tasks := []Task{
{Interval: time.Second, Funcs: app.ScheduledTasks.EverySecond},
{Interval: time.Minute, Funcs: app.ScheduledTasks.EveryMinute},
{Interval: time.Hour, Funcs: app.ScheduledTasks.EveryHour},
{Interval: 24 * time.Hour, Funcs: app.ScheduledTasks.EveryDay},
{Interval: 7 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryWeek},
{Interval: 30 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryMonth},
{Interval: 365 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryYear},
}
// Set up task runners
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
go func(f func(app *App)) {
defer func() { <-runner }()
f(app)
}(f)
}
case <-stop:
return
}
}
}(task, runner)
}
2023-04-06 14:55:56 +00:00
// Wait for all goroutines to finish
wg.Wait()
// Close channels
2023-04-04 19:37:23 +00:00
for _, runner := range runners {
close(runner)
}
}