mirror of https://gitlab.com/ngerakines/tavern.git
37 lines
775 B
Go
37 lines
775 B
Go
package job
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/oklog/run"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type Job interface {
|
|
Run(context.Context) error
|
|
Shutdown(context.Context) error
|
|
}
|
|
|
|
func RunWorker(group *run.Group, logger *zap.Logger, j Job, parent context.Context) {
|
|
group.Add(func() error {
|
|
logger.Info("starting job")
|
|
return ignoreCanceled(j.Run(parent))
|
|
}, func(error) {
|
|
shutdownCtx, shutdownCtxCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer shutdownCtxCancel()
|
|
logger.Info("stopping publisher")
|
|
err := ignoreCanceled(j.Shutdown(shutdownCtx))
|
|
if err != nil {
|
|
logger.Error("error stopping job", zap.Error(err))
|
|
}
|
|
})
|
|
}
|
|
|
|
func ignoreCanceled(err error) error {
|
|
if err == nil || err == context.Canceled {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|