N小时后如何调用函数X

func (timeTables) GetTimeTables(c echo.Context) error {


    resp, err := http.Get("url")

    if err != nil {

        log.Fatal(err)

    }


    body, err := ioutil.ReadAll(resp.Body)


    test := &models.MultiModel{}

    json.Unmarshal(body, &test)

    return c.JSON(http.StatusOK,"")

}

如何在 1 小时后调用 func GetTimeTables,我使用 AferFunc,我缺少什么?


func (timeTables) CallFunc() {

    time.AfterFunc(4*time.Hour, func() {

        GetTimeTables(c echo.Context)

    })

}


一只斗牛犬
浏览 87回答 3
3回答

茅侃侃

你的程序需要阻塞,否则,它会在AfterFunc触发之前退出。尝试从此示例中删除睡眠https://play.golang.org/p/_25RffWDyPV来查看。GetTimeTables不是可以直接调用的函数,您需要将其作为 timeTables 对象的方法来调用。另外,正如 @icza 所提到的,您应该向该函数传递一个值。像这样的东西应该有效:func (t timeTables) CallFunc(c echo.Context) {    time.AfterFunc(4*time.Hour, func() {        t.GetTimeTables(c)    })}

杨__羊羊

我看到c.JSON(http.StatusOK, "")那里,所以我假设代码是一个路由处理程序(使用了 echo 框架)。如果您想尝试的是:对于每个传入的 http 请求,等待 4 小时,然后运行GetTimeTables(); 那么你的http请求将会因为超时而失败。也time.AfterFunc将异步执行(作为 goroutine),因此 http 请求将在回调执行之前完成。也许请详细告诉用户您想要实现的目标。

翻阅古今

我使用 echo 框架执行 myAPI,myAPI 将通过 func GetTimeTables 调用其他 API。你的意思是:func (t timeTables) CallFunc(c echo.Context) {    time.AfterFunc(4*time.Hour, func() {        t.GetTimeTables("myAPI")    })}
打开App,查看更多内容
随时随地看视频慕课网APP