gormlock

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2023 License: MIT Imports: 4 Imported by: 0

README

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

  • The table cron_job_locks needs to exist in the database. This can be achieved, as an example, using gorm automigrate functionality db.Automigrate(&CronJobLock{})
  • In order to uniquely identify the job, the locker uses the unique combination of the job name + timestamp (by default with precision to seconds).

FAQ

  • Q: The locker uses the unique combination of the job name + timestamp with seconds precision, how can I change that?
    • A: It's possible to set how to create the job identifier, here is an example to set an hour precision:
      locker, err := gormlock.NewGormLocker(db, "local",
      	gormlock.WithJobIdentifier(
      		func(ctx context.Context, key string) string {
      			return time.Now().Truncate(60 * time.Minute).
      				Format("2006-01-02 15:04:05.000")
      		},
      	),
      )
      

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewGormLocker

func NewGormLocker(db *gorm.DB, worker string, options ...LockOption) (gocron.Locker, error)

Types

type CronJobLock

type CronJobLock struct {
	ID            int
	CreatedAt     time.Time
	UpdatedAt     time.Time
	JobName       string `gorm:"index:idx_name,unique"`
	JobIdentifier string `gorm:"index:idx_name,unique"`
	Worker        string `gorm:"not null;default:null"`
	Status        string `gorm:"not nullldefault:null"`
}

func (*CronJobLock) GetID

func (cjb *CronJobLock) GetID() int

func (*CronJobLock) SetJobIdentifier

func (cjb *CronJobLock) SetJobIdentifier(ji string)

type JobLock

type JobLock[T any] interface {
	GetID() T
	SetJobIdentifier(ji string)
}

type LockOption

type LockOption func(*gormLocker)

func WithJobIdentifier

func WithJobIdentifier(f func(ctx context.Context, key string) string) LockOption

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL