登录
首页 >  Golang >  Go问答

使用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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>