restart or shutdown golang apps programmatically

huangapple go评论68阅读模式
英文:

restart or shutdown golang apps programmatically

问题

所以我需要编写一个程序,可以通过编程方式运行、重新启动或关闭。我需要从终端执行以下操作:

project> go run app.go
应用已启动,等待5秒...
project>

另一种情况:

project> go run app.go runner.go
从app.go启动应用
从runner.go检测到app.go
应用在10秒后从app.go重新启动

程序将类似于以下内容:

package main

import (
    "something"
)

func main() {
    something.KillPrograms({
        doingWhatever() //这里是我的程序
    }, 5000) //程序将仅运行5秒钟
}

有没有什么库或者Go语言的东西可以做到这样的效果?谢谢。

英文:

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.

答案1

得分: 2

你可以尝试使用time.Sleep

package main

import (
    "fmt"
    "time"
)

func main() {
    // 使用goroutine将函数单独运行
    // 如果你想要同步执行,可以移除`go`
    go 做一些事情()

    // 程序将在5秒后退出
    // 即使你的函数还没有执行完毕
    time.Sleep(5 * time.Second)

    os.Exit(0)
}

请注意,这是一个示例代码,其中的做一些事情()函数需要根据你的实际需求进行定义和实现。

英文:

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)
}

答案2

得分: 1

许多库可以处理程序的重启和监视。查看这个答案或者这个

我刚刚尝试了这段简单的代码,它会每2秒重新启动自己,并在此期间运行一个随机检查来关闭程序。

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)

	// 你可以通过编程方式处理重启
	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())
	// 你可以通过编程方式处理关闭
	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 不支持 exec 系统调用。
	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)
}

输出结果:

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

进程以退出码 0 结束
英文:

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 (
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;os&quot;
	&quot;os/exec&quot;
	&quot;runtime&quot;
	&quot;sync&quot;
	&quot;syscall&quot;
	&quot;time&quot;
)

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()
		&lt;-t1.C
		fmt.Println(&quot;Timer expired&quot;)
		RestartSelf()
	}()

	fmt.Println(time.Now().Format(&quot;2006-Jan-02 ( 15:04:05)&quot;))
	rand.Seed(time.Now().UnixNano())
	// you can handle the shut-down programmatically
	if rand.Intn(3) == 1 {
		fmt.Println(&quot;It is time to shut-down&quot;)
		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 == &quot;windows&quot; {
		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

huangapple
  • 本文由 发表于 2022年3月10日 11:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/71418671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定