Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add background sync worker #24

Merged
merged 3 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions pkg/bsync/bsync.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package bsync

import (
"sync"
"time"
)

type LocalReader[T any] interface {
Get() (T, time.Time)
}

// Worker support for background sync local state.
type Worker[T any] struct {
interval time.Duration
stop chan struct{}
fetchFunc func() (T, error)
localValue T
localTime time.Time
lock sync.Mutex
}

func New[T any](updateInternal time.Duration, fetchFunc func() (T, error)) *Worker[T] {
return &Worker[T]{
interval: updateInternal,
fetchFunc: fetchFunc,
stop: make(chan struct{}, 1),
}
}

func (w *Worker[T]) setValue(v T) {
w.lock.Lock()
defer w.lock.Unlock()
w.localValue = v
w.localTime = time.Now()
}

func (w *Worker[T]) Get() (T, time.Time) {
w.lock.Lock()
defer w.lock.Unlock()
return w.localValue, w.localTime
onlylove97 marked this conversation as resolved.
Show resolved Hide resolved
}

func (w *Worker[T]) Start() {
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
if v, err := w.fetchFunc(); err == nil {
w.setValue(v)
}
for {
select {
case <-w.stop:
break
case <-ticker.C:
v, err := w.fetchFunc()
if err != nil { // user should handle error themself.
continue
}
w.setValue(v)
}
}
}

func (w *Worker[T]) Stop() {
w.stop <- struct{}{}
}
23 changes: 23 additions & 0 deletions pkg/bsync/bsync_worker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package bsync_test

import (
"testing"
"time"

"github.com/KyberNetwork/tradinglib/pkg/bsync"
)

func TestWorker(t *testing.T) {
v := 0
w := bsync.New(time.Millisecond, func() (int, error) {
v++
return v, nil
})
go w.Start()
for i := 0; i < 10; i++ {
c, at := w.Get()
t.Log(c, at)
time.Sleep(time.Millisecond)
}
w.Stop()
}
Loading