46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
// Package inflation contains the background worker that refreshes
|
|
// the price_snapshots table used by the dashboard charts.
|
|
package inflation
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"time"
|
|
|
|
"git.seaofstars.xyz/mohd/deflated/internal/db"
|
|
)
|
|
|
|
// StartRefreshWorker runs in a goroutine and refreshes price snapshots
|
|
// every interval. Call this from main() after connecting to the database.
|
|
//
|
|
// Example:
|
|
//
|
|
// go inflation.StartRefreshWorker(ctx, queries, 1*time.Hour)
|
|
func StartRefreshWorker(ctx context.Context, q *db.Queries, interval time.Duration) {
|
|
// Run once immediately on startup so the charts aren't empty
|
|
runRefresh(ctx, q)
|
|
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
runRefresh(ctx, q)
|
|
case <-ctx.Done():
|
|
log.Println("inflation refresh worker stopped")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func runRefresh(ctx context.Context, q *db.Queries) {
|
|
start := time.Now()
|
|
// using RebuildSnapshots instead of refreshsnapshots for now
|
|
if err := q.RebuildSnapshots(ctx); err != nil {
|
|
log.Printf("error refreshing price snapshots: %v", err)
|
|
return
|
|
}
|
|
log.Printf("price snapshots refreshed in %s", time.Since(start).Round(time.Millisecond))
|
|
}
|