mirror of
https://github.com/sablierapp/sablier.git
synced 2026-01-02 02:57:25 +01:00
feat: add persistent storage (#30)
* refactor: remove unused default timeout * feat: add persistent storage Allows you to save the state to a file and load it upon restarting the app to restore the previous state. * chore: upgrade to go 1.18 * use tinykv with generics * build: add "-buildvcs=false" flag Git is not available in golang:1.18-alpine image
This commit is contained in:
62
pkg/storage/periodic_sync.go
Normal file
62
pkg/storage/periodic_sync.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PS interface {
|
||||
Stop()
|
||||
}
|
||||
|
||||
type PeriodicSync struct {
|
||||
File *os.File
|
||||
Interval time.Duration
|
||||
Content interface{}
|
||||
|
||||
stop chan struct{}
|
||||
stopOnce sync.Once
|
||||
}
|
||||
|
||||
func New(file *os.File, interval time.Duration, content interface{}) PS {
|
||||
sync := &PeriodicSync{
|
||||
File: file,
|
||||
Interval: interval,
|
||||
Content: content,
|
||||
stop: make(chan struct{}),
|
||||
}
|
||||
|
||||
go sync.syncLoop()
|
||||
|
||||
return sync
|
||||
}
|
||||
|
||||
func (sync *PeriodicSync) Stop() {
|
||||
sync.stopOnce.Do(func() { close(sync.stop) })
|
||||
}
|
||||
|
||||
func (sync *PeriodicSync) save() error {
|
||||
sync.File.Truncate(0)
|
||||
sync.File.Seek(0, 0)
|
||||
return json.NewEncoder(sync.File).Encode(sync.Content)
|
||||
}
|
||||
|
||||
func (sync *PeriodicSync) syncLoop() {
|
||||
interval := sync.Interval
|
||||
expireTime := time.NewTimer(interval)
|
||||
for {
|
||||
select {
|
||||
case <-sync.stop:
|
||||
return
|
||||
case <-expireTime.C:
|
||||
err := sync.save()
|
||||
if err != nil {
|
||||
log.Println("Error saving", err)
|
||||
}
|
||||
expireTime.Reset(interval)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user