Вот скрипт, который позволяет вам установить время ожидания программы и динамически изменять время ожидания во время выполнения. 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)
}