From b300ad869f424cdd26bcfc78635a27656836ca96 Mon Sep 17 00:00:00 2001 From: GrailFinder Date: Wed, 12 Jun 2024 09:13:05 +0300 Subject: Feat: add cron and defaults table --- internal/crons/main.go | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 internal/crons/main.go (limited to 'internal/crons') diff --git a/internal/crons/main.go b/internal/crons/main.go new file mode 100644 index 0000000..9655522 --- /dev/null +++ b/internal/crons/main.go @@ -0,0 +1,88 @@ +package crons + +import ( + "apjournal/internal/database/repos" + "context" + "os" + "strconv" + "time" + + "log/slog" +) + +var ( + log = slog.New(slog.NewJSONHandler(os.Stdout, + &slog.HandlerOptions{Level: slog.LevelDebug})) +) + +const ( + CheckBurnTimeKey = "check_burn_time_key" +) + +type Cron struct { + ctx context.Context + repo repos.FullRepo +} + +func NewCron( + ctx context.Context, repo repos.FullRepo, +) *Cron { + return &Cron{ + ctx: ctx, + repo: repo, + } +} + +func (c *Cron) UpdateDefaultsFloat64(defaults map[string]float64) (map[string]float64, error) { + dm, err := c.repo.DBGetDefaultsMap() + if err != nil { + return defaults, err + } + for k, _ := range defaults { + sosValue, ok := dm[k] + if ok { + value, err := strconv.ParseFloat(sosValue, 64) + if err != nil { + // log err + continue + } + defaults[k] = value + } + } + return defaults, nil +} + +func (c *Cron) StartCronJobs() { + // check system_options for time + defaults := map[string]float64{ + CheckBurnTimeKey: 5.0, + } + defaults, err := c.UpdateDefaultsFloat64(defaults) + if err != nil { + panic(err) + } + go c.BurnTicker( + time.Minute * time.Duration(defaults[CheckBurnTimeKey])) +} + +func (c *Cron) BurnTicker(interval time.Duration) { + funcname := "BurnTicker" + ticker := time.NewTicker(interval) + for { + select { + case <-c.ctx.Done(): + log.Info("cron stopped by ctx.Done", "func", funcname) + return + case <-ticker.C: + c.BurnTimeUpdate() + } + } +} + +func (c *Cron) BurnTimeUpdate() { + // funcname := "BurnTimeUpdate" + // get all user scores + // if burn time < now + // halv the score + // move the burn time to 24h from now (using same hours, minutes, seconds) +} -- cgit v1.2.3