英文:
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)
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论