From 47e23fda9021df3abc8bf78ebd566d5a7a22118f Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 6 Jan 2022 23:57:42 +0800 Subject: [PATCH] bbgo: add cache expiry --- pkg/bbgo/cache.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pkg/bbgo/cache.go b/pkg/bbgo/cache.go index 353c656f5..65fa56fc3 100644 --- a/pkg/bbgo/cache.go +++ b/pkg/bbgo/cache.go @@ -8,14 +8,18 @@ import ( "os" "path" "reflect" + "time" - "github.com/c9s/bbgo/pkg/types" "github.com/pkg/errors" log "github.com/sirupsen/logrus" + + "github.com/c9s/bbgo/pkg/types" ) 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, // The key must be an unique ID. // obj is the pointer of your local variable @@ -24,8 +28,9 @@ func WithCache(key string, obj interface{}, fetcher DataFetcher) error { cacheDir := CacheDir() cacheFile := path.Join(cacheDir, key+".json") - if _, err := os.Stat(cacheFile); os.IsNotExist(err) { - log.Debugf("cache %s not found, executing fetcher callback to get the data", cacheFile) + stat, err := os.Stat(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() if err != nil {