在PHP中,我们有ini_set('max_execution_time', 180)
,通过它我们可以即时更改执行时间。
Go中有与此类似的东西吗?
答案 0 :(得分:0)
这里有一个脚本,该脚本使您可以设置程序超时并在执行期间动态更改超时。 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)
}