How to store data to redis at specific Time interval in Go

huangapple go评论90阅读模式
英文:

How to store data to redis at specific Time interval in Go

问题

我正在尝试在Redis中设置数据(在上午6点、下午12点、下午6点和凌晨12点)。但我只能为数据缓存设置过期时间。在Golang中有没有办法做到这一点?

代码:

err := client.Set(key, data[]byte, 6 * time.Hour).Err()
英文:

I am trying to Set Data to Redis at (6 am, 12 pm, 6 pm and 12 am). But all I can do is setting an expiration time for data caching in redis. Is there any way in Golang to do this?

Code:

err := client.Set(key, data[]byte, 6 * time.Hour).Err()

答案1

得分: 1

由于您希望每6小时向Redis中添加数据,您应该使用cronjob来实现。

我创建了一个示例场景,可能会对您有所帮助,如下所示:

为了更好地理解,您可以参考gocron包。

s := gocron.NewScheduler(time.UTC)

s.Every(6).Hours().Do(func(){  //您可以根据需要更改时间间隔

  err := client.Set(ctx, "key", "value", 0).Err()  //您的逻辑
    if err != nil {
        panic(err)
    }

})
英文:

Since you want to add data in redis at evry 6 hours. You should use cronjob for this.

I have created a sample scenario which might help you as follows:

For better understanding you can refer gocron package.

s := gocron.NewScheduler(time.UTC)
    
    s.Every(6).Hours().Do(func(){  //you can change it
    
      err := client.Set(ctx, "key", "value", 0).Err()  //your logic
        if err != nil {
            panic(err)
        }
    
     })

huangapple
  • 本文由 发表于 2021年12月6日 20:43:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70245695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定