【问题标题】:How to increase the server timeout on the fly如何即时增加服务器超时
【发布时间】:2019-11-06 10:11:37
【问题描述】:

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

【问题讨论】:

  • 不,没有。这在 Go 中也没有什么意义,因为 Go 不像 PHP 那样是单线程的。
  • Go 提供的唯一类似的超时是 http.Server 结构中的各种超时。而且它们只能在启动时设置(尽管您可以构建一个程序,在配置更改时重新启动服务器,而无需重新启动整个过程——但可能不值得)
  • 一种更动态的方法是为每个连接设置上下文超时(可能在中间件中)。无需重新启动即可轻松完成此操作,但只会影响新连接。
  • @AyushGupta:不过,您无法在不重新启动的情况下重置 ENV 变量。
  • @AyushGupta:见这里:stackoverflow.com/q/205064/13860 TL;DR;在进程运行时更改环境变量的方法有很多,但是没有标准的方法来告诉进程重新读取环境变量,所以在实践中,这是不可能的。 (而且我确信 Go 运行时不支持它,所以你会被困在做一些低级系统调用来重新读取 env)

标签: go server


【解决方案1】:

这是一个脚本,允许您设置程序超时并在执行期间动态更改超时。 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)
}

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 2010-12-03
    • 2016-02-12
    • 2023-02-22
    • 2018-07-31
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多