replace slot attempts int with atomics

This commit is contained in:
rmanach 2024-09-24 12:29:41 +02:00
parent b6df47ed0c
commit 3cbea438f6

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
@ -35,36 +36,32 @@ type JobSlotDetails struct {
} }
type jobSlot struct { type jobSlot struct {
l sync.RWMutex *job.Job
job.Job slot atomic.Uint32
slot int attempts atomic.Uint32
attempts int
// priority Priority // priority Priority
} }
func newJobSlot(task job.FnJob, slot int) jobSlot { func newJobSlot(task job.FnJob, slot int) *jobSlot {
return jobSlot{ j := job.NewJob(task)
Job: job.NewJob(task), js := jobSlot{
slot: slot, Job: &j,
} }
js.slot.Add(uint32(slot))
return &js
} }
func (j *jobSlot) run(ctx context.Context) { func (j *jobSlot) run(ctx context.Context) {
j.l.Lock() j.attempts.Add(1)
defer j.l.Unlock()
j.attempts += 1
j.Job.Run(ctx) j.Job.Run(ctx)
} }
func (j *jobSlot) getDetails() JobSlotDetails { func (j *jobSlot) getDetails() JobSlotDetails {
j.l.RLock()
defer j.l.RUnlock()
return JobSlotDetails{ return JobSlotDetails{
JobDetails: j.IntoDetails(), JobDetails: j.IntoDetails(),
Attempts: j.attempts, Attempts: int(j.attempts.Load()),
} }
} }
@ -175,8 +172,8 @@ func (c *SchedulerCycle) Delay(fnJob job.FnJob) uuid.UUID {
j := newJobSlot(fnJob, nextSlot) j := newJobSlot(fnJob, nextSlot)
c.slots[nextSlot] = append(c.slots[nextSlot], &j) c.slots[nextSlot] = append(c.slots[nextSlot], j)
c.jobs[j.GetID()] = &j c.jobs[j.GetID()] = j
log.Info().Str("job", j.GetID().String()).Msg("job added successfully") log.Info().Str("job", j.GetID().String()).Msg("job added successfully")
return j.GetID() return j.GetID()
@ -329,6 +326,7 @@ func (c *SchedulerCycle) updateCurrentSlot(j *jobSlot) {
c.l.Lock() c.l.Lock()
defer c.l.Unlock() defer c.l.Unlock()
j.slot.CompareAndSwap(j.slot.Load(), uint32(c.currentSlot))
c.slots[c.currentSlot] = append(c.slots[c.currentSlot], j) c.slots[c.currentSlot] = append(c.slots[c.currentSlot], j)
} }