mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-22 23:05:15 +00:00
bbgo: add cache expiry
This commit is contained in:
parent
1d5406ef21
commit
47e23fda90
|
@ -8,14 +8,18 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/c9s/bbgo/pkg/types"
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
|
|
||||||
|
"github.com/c9s/bbgo/pkg/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DataFetcher func() (interface{}, error)
|
type DataFetcher func() (interface{}, error)
|
||||||
|
|
||||||
|
const cacheExpiry = 24 * time.Hour
|
||||||
|
|
||||||
// WithCache let you use the cache with the given cache key, variable reference and your data fetcher,
|
// WithCache let you use the cache with the given cache key, variable reference and your data fetcher,
|
||||||
// The key must be an unique ID.
|
// The key must be an unique ID.
|
||||||
// obj is the pointer of your local variable
|
// obj is the pointer of your local variable
|
||||||
|
@ -24,8 +28,9 @@ func WithCache(key string, obj interface{}, fetcher DataFetcher) error {
|
||||||
cacheDir := CacheDir()
|
cacheDir := CacheDir()
|
||||||
cacheFile := path.Join(cacheDir, key+".json")
|
cacheFile := path.Join(cacheDir, key+".json")
|
||||||
|
|
||||||
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
|
stat, err := os.Stat(cacheFile)
|
||||||
log.Debugf("cache %s not found, executing fetcher callback to get the data", cacheFile)
|
if os.IsNotExist(err) || (stat != nil && time.Since(stat.ModTime()) > cacheExpiry) {
|
||||||
|
log.Debugf("cache %s not found or cache expired, executing fetcher callback to get the data", cacheFile)
|
||||||
|
|
||||||
data, err := fetcher()
|
data, err := fetcher()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
Loading…
Reference in New Issue
Block a user