A gocron locker implementation using gorm
go get github.com/go-co-op/gocron-gorm-lock
Here is an example usage that would be deployed in multiple instances
package main
import (
"fmt"
"github.com/go-co-op/gocron"
gormlock "github.com/go-co-op/gocron-gorm-lock"
"gorm.io/gorm"
"time"
)
func main() {
var db * gorm.DB // gorm db connection
var worker string // name of this instance to be used to know which instance run the job
db.AutoMigrate(&CronJobLock{}) // We need the table to store the job execution
locker, err := gormlock.NewGormLocker(db, worker)
if err != nil {
// handle the error
}
s := gocron.NewScheduler(time.UTC)
s.WithDistributedLocker(locker)
_, err = s.Every("1s").Name("unique_name").Do(func() {
// task to do
fmt.Println("call 1s")
})
if err != nil {
// handle the error
}
s.StartBlocking()
}
db.Automigrate(&CronJobLock{})
locker, err := gormlock.NewGormLocker(db, "local", gormlock.WithDefaultJobIdentifier(60 * time.Minute))
locker, err := gormlock.NewGormLocker(db, "local",
gormlock.WithJobIdentifier(
func(ctx context.Context, key string) string {
return ...
},
),
)