replace lock with atomic
This commit is contained in:
parent
152c4f925a
commit
ec53ec990a
@ -3,36 +3,33 @@ package scheduler
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"cycle-scheduler/internal/job"
|
"cycle-scheduler/internal/job"
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// safeTime wraps a `time.Timer` with a lock to be thread safe.
|
// atomicTimer wraps a `time.Timer`.
|
||||||
type safeTimer struct {
|
type atomicTimer struct {
|
||||||
l sync.Mutex
|
atomic.Pointer[time.Timer]
|
||||||
timer *time.Timer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (st *safeTimer) stop() {
|
func (at *atomicTimer) stop() {
|
||||||
if st.timer != nil {
|
timer := at.Load()
|
||||||
st.timer.Stop()
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// set replaces the current timer.
|
// set replaces the current timer.
|
||||||
// It also ensures that the current timer is stopped.
|
// It also ensures that the current timer is stopped.
|
||||||
func (st *safeTimer) set(t *time.Timer) {
|
func (at *atomicTimer) set(t *time.Timer) {
|
||||||
st.l.Lock()
|
timer := at.Load()
|
||||||
defer st.l.Unlock()
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
if st.timer != nil {
|
at.Swap(t)
|
||||||
st.timer.Stop()
|
|
||||||
st.timer = t
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
st.timer = t
|
at.Swap(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
type TaskDetails struct {
|
type TaskDetails struct {
|
||||||
@ -43,23 +40,21 @@ type TaskDetails struct {
|
|||||||
type task struct {
|
type task struct {
|
||||||
*job.Job
|
*job.Job
|
||||||
attempts atomic.Uint32
|
attempts atomic.Uint32
|
||||||
timer *safeTimer
|
timer atomicTimer
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTask(f job.FnJob) *task {
|
func newTask(f job.FnJob) *task {
|
||||||
j := job.NewJob(f)
|
j := job.NewJob(f)
|
||||||
t := task{
|
t := task{
|
||||||
Job: &j,
|
Job: &j,
|
||||||
timer: &safeTimer{},
|
timer: atomicTimer{},
|
||||||
}
|
}
|
||||||
|
|
||||||
return &t
|
return &t
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *task) abort() {
|
func (t *task) abort() {
|
||||||
if t.timer != nil {
|
|
||||||
t.timer.stop()
|
t.timer.stop()
|
||||||
}
|
|
||||||
t.Job.Abort()
|
t.Job.Abort()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user