Skip to content

Instantly share code, notes, and snippets.

@vmpartner
Created October 15, 2019 19:36
Show Gist options
  • Save vmpartner/ca646c1d9639a8636206baa91785e2ab to your computer and use it in GitHub Desktop.
Save vmpartner/ca646c1d9639a8636206baa91785e2ab to your computer and use it in GitHub Desktop.
Example how make unkillable golang app
package main
import (
"fmt"
"time"
)
var chExit chan struct{}
const TimeSleepRecover = 10
func main() {
go Run()
select {}
}
func Run() {
chExit = make(chan struct{})
defer Recover(TimeSleepRecover, Run, chExit)
go R1()
go R2()
}
func R1() {
for {
select {
default:
time.Sleep(2 * time.Second)
fmt.Println("R1")
case <-chExit:
return
}
}
}
func R2() {
defer Recover(TimeSleepRecover, Run, chExit)
for {
select {
default:
time.Sleep(7 * time.Second)
fmt.Println("R2")
panic("123")
case <-chExit:
return
}
}
}
func Recover(d time.Duration, f func(), chExit chan struct{}) {
if r := recover(); r != nil {
fmt.Printf("Recover error %+v Stop goroutines\n", r)
close(chExit)
fmt.Printf("Sleep %d\n", d)
time.Sleep(d * time.Second)
f()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment