starryrbs / gocron-redis-lock

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

redislock

CI State Go Report Card Go Doc

install

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

usage

Here is an example usage that would be deployed in multiple instances

package main

import (
	"fmt"
	"time"

	"github.com/go-co-op/gocron"
	"github.com/redis/go-redis/v9"

	redislock "github.com/go-co-op/gocron-redis-lock"
)

func main() {
	redisOptions := &redis.Options{
		Addr: "localhost:6379",
	}
	redisClient := redis.NewClient(redisOptions)
	locker, err := redislock.NewRedisLocker(redisClient, redislock.WithTries(1))
	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()
}

The redis UniversalClient can also be used

package main

import (
	"fmt"
	"time"

	"github.com/go-co-op/gocron"
	"github.com/redis/go-redis/v9"

	redislock "github.com/go-co-op/gocron-redis-lock"
)

func main() {
	redisOptions := &redis.UniversalOptions{
		Addrs: []string{"localhost:6379"},
	}
	redisClient := redis.NewUniversalClient(redisOptions)
	locker, err := redislock.NewRedisLocker(redisClient, redislock.WithTries(1))
	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()
}

About

License:MIT License


Languages

Language:Go 94.2%Language:Makefile 5.8%