Package worker adding the abstraction layer around background jobs, allows make a job periodically, observe execution time and to control concurrent execution.
Group of workers allows to control jobs start time and wait until all runned workers finished when we need stop all jobs.
- Scheduling, use one from existing
worker.By*
schedule functions. Supporting cron schedule spec format by robfig/cron parser. - Control concurrent execution around multiple instances by
worker.WithLock
. See existing lockers - Observe a job execution time duration with
worker.SetObserever
. Friendly for prometheus/client_golang package. - Graceful stop, wait until all running jobs was completed.
wg := worker.NewGroup()
wg.Add(
worker.
New(func(context.Context) {}).
ByTicker(time.Second),
worker.
New(func(context.Context) {}).
ByTimer(time.Second),
worker.
New(func(context.Context) {}).
ByCronSpec("@every 1s"),
)
wg.Run()
You can use redis locks for controll exclusive job execution:
l := locker.NewRedis(radix.Client, "job_lock_name", locker.RedisLockTTL(time.Minute))
w := worker.
New(func(context.Context) {}).
WithLock(l)
// Job will be executed only if `job_lock_name` redis key not exists.
w.Run(context.Background())