Skip to content

Commit

Permalink
refactor(runner): use sync.Once instead of sync.Mutex
Browse files Browse the repository at this point in the history
Signed-off-by: Dwi Siswanto <[email protected]>
  • Loading branch information
dwisiswant0 committed Oct 2, 2023
1 parent d68d7af commit d327410
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
30 changes: 13 additions & 17 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ type Runner struct {
*cron.Cron
*http.Server

shuttingDown bool
shutdownLock sync.Mutex
telerOpts teler.Options
shutdown shutdown
telerOpts teler.Options
watcher
}

Expand Down Expand Up @@ -74,6 +73,7 @@ func New(opt *common.Options) error {

run.Server = server
run.telerOpts = tun.Options
run.shutdown.Once = new(sync.Once)

if run.shouldCron() && run.Cron == nil {
w, err := fsnotify.NewWatcher()
Expand Down Expand Up @@ -145,27 +145,23 @@ func (r *Runner) start() error {
return nil
}

func (r *Runner) shutdown() error {
r.shutdownLock.Lock()
defer r.shutdownLock.Unlock()
func (r *Runner) stop() error {
r.shutdown.Do(func() {
r.Options.Logger.Info("Gracefully shutdown...")

if r.shuttingDown {
return nil
}
r.shuttingDown = true

r.Options.Logger.Info("Gracefully shutdown...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.shutdown.err = r.Server.Shutdown(ctx)
})

return r.Server.Shutdown(ctx)
return r.shutdown.err
}

func (r *Runner) restart() error {
r.Options.Logger.Info("Restarting...")

if err := r.shutdown(); err != nil {
if err := r.stop(); err != nil {
return err
}

Expand All @@ -177,7 +173,7 @@ func (r *Runner) notify(sigCh chan os.Signal) error {

switch sig {
case syscall.SIGINT, syscall.SIGTERM:
return r.shutdown()
return r.stop()
case syscall.SIGHUP:
return r.restart()
}
Expand Down
9 changes: 9 additions & 0 deletions internal/runner/shutdown.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package runner

import "sync"

type shutdown struct {
*sync.Once

err error
}

0 comments on commit d327410

Please sign in to comment.