Skip to content
/ worker Public

Simple abstraction for control background jobs

License

Notifications You must be signed in to change notification settings

chapsuk/worker

Repository files navigation

Worker

GoDoc Build Status codecov Go Report Card codebeat badge

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.

Features

  • 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.

Example

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()

Lockers

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())