使用Golang编写一个基于Web的服务,在计时器到期时自动重新启动计时器
来源:stackoverflow
时间:2024-02-10 10:18:22 291浏览 收藏
小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《使用Golang编写一个基于Web的服务,在计时器到期时自动重新启动计时器》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
问题内容
我想在服务器端代码中编写此功能。是否有有效的方法来编写在后台运行一定时间的功能,并且当持续时间到期时触发事件。之后,它会重新启动计时器以一次又一次地触发下一次事件。
我想异步执行此操作,就像计时器启动一样在后台运行,并在到期时调用要执行的函数。函数完成执行后,它会再次异步触发事件/函数,从而重新启动计时器,而无需在代码中的任何位置等待。
每次都会动态计算持续时间。
我尝试使用下面的方法,但它等待通道,我必须运行 for 循环,这也会阻止代码。
import ( "encoding/json" "fmt" "io/ioutil" "os" "strconv" "strings" "time" ) const interval_period time.duration = 24 * time.hour var hour_to_tick int var minute_to_tick int var second_to_tick int type jobticker struct { t *time.timer } func setconfig(appconfs map[string]string) bool { timeofeventtrigger := appconfs["task_trigger_time"] clocktime := strings.split(timeofeventtrigger, ":") fmt.println("fixed clock time to trigger event ", clocktime) hour_to_tick, _ = strconv.atoi(clocktime[0]) minute_to_tick, _ = strconv.atoi(clocktime[1]) second_to_tick, _ = strconv.atoi(clocktime[2]) return true } func readconfigfromjson(configpath string) bool { fmt.printf("loading configurations from %s\n", configpath) configmap := map[string]string{} configfile, err := os.open(configpath) if err != nil { fmt.printf("unable to the load the config: %v\n", err) return false } bytevalue, err := ioutil.readall(configfile) if err != nil { fmt.printf("unable to decode the config: %v\n", err) return false } err = json.unmarshal(bytevalue, &configmap) if err != nil { fmt.printf("unable to unmarshal to json: %v\n", err) return false } defer configfile.close() return setconfig(configmap) } func getnexttickduration() time.duration { now := time.now() nexttick := time.date(now.year(), now.month(), now.day(), hour_to_tick, minute_to_tick, second_to_tick, 0, time.local) if nexttick.before(now) { nexttick = nexttick.add(interval_period) } fmt.println("current time is -> ", now) fmt.println(" next trigger at this date and time - ", nexttick) waitduration := nexttick.sub(time.now()) fmt.println(" clock is waiting for duration -> ", waitduration) return waitduration } func newjobticker() jobticker { fmt.println("genrate new job ticker here") return jobticker{time.newtimer(getnexttickduration())} } func (jt jobticker) updatejobticker() { fmt.println("update job ticker here") jt.t.reset(getnexttickduration()) } func starttmer () { jt := newjobticker() for { <-jt.t.c fmt.println(time.now(), "- just ticked") // do our logic jt.updatejobticker() } }
这里是执行事件时正在读取的 json 文件。
// config.json { "Task_Trigger_Time": "12:30:00" }
正确答案
对原始代码添加了一些更改。这可以处理恐慌,以防在读取持续时间时发生恐慌,并使用 time.sleep
而不是 time.afterfunc
。
//start the timer again func performoutdatedoperationforstore() { // do somthing // start the timer again timedurationtowait,err := getnexttickduration() if err!=nil{ //log error } go starttimeduration(timedurationtowait) } func starttimeduration(timedurationtowait string) { // start timer time.sleep(timedurationtowait) performoutdatedoperationforstore() //time.afterfunc(timedurationtowait, func() { performoutdatedoperationforstore() }): this calls performoutdatedoperationforstore() in a new go routine, which is also ok, but not nesseccary. }
嗨,我已经这样做了。如果可能的话,请简要建议一个更好的方法。 我是一个完全的新手,它会对我有很大帮助......
//start the timer again func performOutdatedOperationForStore() { // do somthing // start the timer again go StartTimeDuration() } func StartTimeDuration() { // start timer timeDurationToWait := getNextTickDuration() // gvalidObjectTime := config.ConfigurationObject.ObjectLifeTimeTTL time.AfterFunc(timeDurationToWait, func() { performOutdatedOperationForStore() }) }
今天关于《使用Golang编写一个基于Web的服务,在计时器到期时自动重新启动计时器》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习