package common import ( "context" "os" "sync" "time" ) const maxTryBeforeReboot = 10 // Disturber stop type Disturber struct { mtx sync.Mutex live bool until int } // NewDisturber new func NewDisturber() *Disturber { return &Disturber{ live: true, until: 0, } } // Prevent prevent func (d *Disturber) Prevent() { d.mtx.Lock() defer d.mtx.Unlock() d.live = true } // MaybeReboot reboot func (d *Disturber) MaybeReboot(ctx context.Context, fn func(...interface{})) { d.live = true for { select { case <-ctx.Done(): return default: d.mtx.Lock() running := d.live d.mtx.Unlock() if running { d.until = 0 d.mtx.Lock() d.live = false d.mtx.Unlock() } else { d.until++ fn("Face No Running: ", d.until) if d.until > maxTryBeforeReboot { fn("Face Too Long Running, Reboot") os.Exit(0) } } time.Sleep(time.Second) } } }