登录
首页 >  Golang >  Go问答

增加服务器超时时间的方法

来源:stackoverflow

时间:2024-03-15 22:21:20 219浏览 收藏

在 PHP 中,`ini_set('max_execution_time', 180)` 可用于动态调整执行时间。本文介绍了 Go 中的类似方法,通过一个脚本实现程序超时设置和执行期间的动态超时调整。该脚本使用一个定时器异步监控并终止程序,并提供了一个 `setTimeout` 函数,用于根据需要动态调整超时时间。这对于处理长时间运行的任务或需要动态调整执行限制的情况非常有用。

问题内容

在 PHP 中,我们有 ini_set('max_execution_time', 180),我们可以通过它动态更改执行时间。 Go 中有类似的东西吗?


解决方案


这是一个脚本,允许您设置程序超时并在执行期间动态更改超时。 https://play.golang.org/p/qRvVMPnp9g2

package main

import (
    "fmt"
    "time"
    "os"
)

var (
    oldDuration time.Duration = 10 * time.Second
    timer *time.Timer = time.NewTimer(oldDuration)
    start time.Time = time.Now()
)

// The init function is called before main
func init(){
    // function asynchronously monitors and terminates script after timeout
    go func(){
        <- timer.C
        fmt.Println("Exit")
        os.Exit(1)
    }()
}

func main() {

    // Do some work
    <-time.After(2 * time.Second)
    fmt.Println("Hello World")

    // Change timeout interval dynamically
    setTimeout(5 * time.Second)

    // Do more work
    <-time.After(5 * time.Second)
    fmt.Println("Shouldn't be reached as script terminates after 5 seconds of which 2 seconds have been used earlier")
}

func setTimeout(newDuration time.Duration){

     // Stop timer - prevent program terminating in setTimeout function
     timer.Stop()

     // Compute remaining time
     var timePassed time.Duration = time.Since(start)
     var timeToTermination time.Duration = newDuration - timePassed

     // Restart timer - continuing from however many second 
     // have elapsed since the program started
     oldDuration = newDuration
     timer.Reset(timeToTermination)
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《增加服务器超时时间的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>