go-co-op / gocron-gorm-lock

A gocron locker implementation using gorm
MIT License
9 stars 5 forks source link

golangci-lint

gocron-gorm-lock

A gocron locker implementation using gorm

install

go get github.com/go-co-op/gocron-gorm-lock

usage

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

Prerequisites

FAQ