Home > Software design >  restart or shutdown golang apps programmatically
restart or shutdown golang apps programmatically

Time:03-11

so i need to make a program than can run, then restart or shutdown programmatically. I need to do like this from terminal:

project> go run app.go
apps started, waiting for 5 sec...
project>

other scenario:

project> go run app.go runner.go
apps started from app.go
runner detecting app.go from runner.go
app restarted after 10 sec from app.go

The program will be something like below:

package main

import(
    "something"
)
func main () {
    something.KillPrograms({
        doingWhatever() //my program here
   }, 5000) //program will running for only 5 sec
}

any library or anything from golang can do like that? thanks.

CodePudding user response:

You can try with time.Sleep

package main

import (
    "fmt"
    "time"
)

func main() {
    //use goroutine to run your function separately
    //if you want it's sync, you can remove `go`
    go doingWhatever()

    //after 5 seconds, the program will exit 
    //even though your function has not been done yet
    time.Sleep(5 * time.Second)

    os.Exit(0)
}

CodePudding user response:

Many libraries can handle restart/watch of the program. check this answer or this one.

I just tried this simple code that will restart itself each 2 seconds and during that he will run a random check to shutdown.

package main

import (
    "fmt"
    "math/rand"
    "os"
    "os/exec"
    "runtime"
    "sync"
    "syscall"
    "time"
)

var wg sync.WaitGroup

func main() {
    t1 := time.NewTimer(time.Second * 2)
    wg.Add(1)

    // you can handle to restart programmatically
    go func() {
        defer wg.Done()
        <-t1.C
        fmt.Println("Timer expired")
        RestartSelf()
    }()

    fmt.Println(time.Now().Format("2006-Jan-02 ( 15:04:05)"))
    rand.Seed(time.Now().UnixNano())
    // you can handle the shut-down programmatically
    if rand.Intn(3) == 1 {
        fmt.Println("It is time to shut-down")
        os.Exit(0)
    }
    wg.Wait()

}
func RestartSelf() error {
    self, err := os.Executable()
    if err != nil {
        return err
    }
    args := os.Args
    env := os.Environ()
    // Windows does not support exec syscall.
    if runtime.GOOS == "windows" {
        cmd := exec.Command(self, args[1:]...)
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        cmd.Stdin = os.Stdin
        cmd.Env = env
        err := cmd.Run()
        if err == nil {
            os.Exit(0)
        }
        return err
    }
    return syscall.Exec(self, args, env)
}


output

2022-Mar-10 ( 17:59:53)
Timer expired
2022-Mar-10 ( 17:59:55)
Timer expired
2022-Mar-10 ( 17:59:57)
It is time to shut-down

Process finished with the exit code 0

  •  Tags:  
  • go
  • Related