2022-05-05 01:56:21 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
2022-06-30 05:48:04 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2022-05-05 01:56:21 +00:00
|
|
|
)
|
|
|
|
|
2022-06-30 05:48:04 +00:00
|
|
|
var graceful = &Graceful{}
|
|
|
|
|
2022-05-05 01:56:21 +00:00
|
|
|
//go:generate callbackgen -type Graceful
|
|
|
|
type Graceful struct {
|
|
|
|
shutdownCallbacks []func(ctx context.Context, wg *sync.WaitGroup)
|
|
|
|
}
|
|
|
|
|
2022-06-30 05:48:04 +00:00
|
|
|
// Shutdown is a blocking call to emit all shutdown callbacks at the same time.
|
2022-05-05 01:56:21 +00:00
|
|
|
func (g *Graceful) Shutdown(ctx context.Context) {
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(len(g.shutdownCallbacks))
|
|
|
|
|
2022-06-30 05:48:04 +00:00
|
|
|
// for each shutdown callback, we give them 10 second
|
|
|
|
shtCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
|
|
|
|
|
|
go g.EmitShutdown(shtCtx, &wg)
|
2022-05-05 01:56:21 +00:00
|
|
|
|
|
|
|
wg.Wait()
|
2022-06-30 05:48:04 +00:00
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
|
|
|
|
func OnShutdown(f func(ctx context.Context, wg *sync.WaitGroup)) {
|
|
|
|
graceful.OnShutdown(f)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Shutdown() {
|
|
|
|
logrus.Infof("shutting down...")
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
|
|
|
|
graceful.Shutdown(ctx)
|
|
|
|
cancel()
|
2022-05-05 01:56:21 +00:00
|
|
|
}
|