mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-10-15 22:39:56 +00:00
* feat(logging): configure levels and structured runtime output * fix(logging): bound request-derived log fields * fix(logging): retain malformed IATA source attributes safely * test(logging): capture structured REST rate-limit records
52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package background runs periodic maintenance tasks on independent schedules.
|
|
package background
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"time"
|
|
)
|
|
|
|
// Task is a named unit of work that runs on a fixed interval.
|
|
type Task struct {
|
|
Name string
|
|
Interval time.Duration
|
|
Run func(ctx context.Context) error
|
|
}
|
|
|
|
// Scheduler runs a set of tasks on independent tickers.
|
|
type Scheduler struct {
|
|
tasks []Task
|
|
}
|
|
|
|
// New creates a Scheduler with the given tasks.
|
|
func New(tasks []Task) *Scheduler {
|
|
return &Scheduler{tasks: tasks}
|
|
}
|
|
|
|
// Start launches each task in its own goroutine. Blocks until ctx is cancelled.
|
|
func (s *Scheduler) Start(ctx context.Context) {
|
|
for _, t := range s.tasks {
|
|
go func() {
|
|
ticker := time.NewTicker(t.Interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
slog.Debug("task running", "component", "background", "task", t.Name)
|
|
if err := t.Run(ctx); err != nil {
|
|
slog.Error("task failed", "component", "background", "task", t.Name, "error", err)
|
|
} else {
|
|
slog.Debug("task complete", "component", "background", "task", t.Name)
|
|
}
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
}
|