schedule

package
v0.12.3 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: MIT Imports: 21 Imported by: 6

README

Schedule Module

This module provides a robust cron job scheduling mechanism with support for both distributed environments (via Redis) and single-instance deployments (RAM mode).

Features

1. Distributed Scheduling (Default)

Designed for high availability in Kubernetes/Cluster environments. It ensures that tasks are executed exactly once across the cluster by restricting execution to a single "Leader" Pod.

  • Mechanism:
    • Leader Election: All Pods compete to become the leader using a Redis Lock (SetNX with TTL). The election Key is scoped by core.AppName to support multi-tenant Redis sharing.
    • Leader-Only Execution: Only the elected Leader Pod will trigger and execute the cron tasks. Non-leader Pods remain in standby.
    • Failover: The Leader periodically renews its lease. If the Leader Pod crashes, the lease expires (default TTL 10s), and a standby Pod is automatically elected as the new Leader to resume operations.
  • Dependencies: Requires Redis.
2. RAM Mode (Simple)

Designed for development or single-instance deployments where Redis is not available or needed.

  • Mechanism: Standard in-memory Cron.
  • Limitations: No concurrency control (NoLocker). If you run multiple replicas, the task will run on every replica.
  • Dependencies: None (In-memory).

Build Tags

The module uses Golang Build Tags to switch implementation details at compile time, similar to pkg/cache.

Mode Build Tag Features Concurrent Control
Default !ram Leader Election, Redis Lock, Job History Yes (Distributed Leader)
RAM ram Local Cron No (None)

Usage

Enable Distributed Mode (Default)

Simply build your project normally. The code defaults to using cron_redis.go.

go build ./...

Configuration: The module automatically registers a startup hook (core.ProvideStartup) to start the leader election process when the application starts. No manual invocation is needed if you use ginshared.Start().

You can configure the Leader Election parameters via your application configuration (e.g., app.yaml):

schedule:
  leader:
    interval: 3s       # Election check interval (default: 3s)
    ttl: 10s           # Leader key validity period (default: 10s)
    key: "my-leader"   # Optional: Override redis key (default: scheduler:<AppName>:leader)

Code Example:

import "github.com/techquest-tech/gin-shared/pkg/schedule"

func main() {
    // ... init redis ...
    
    // Define tasks
    schedule.CreateScheduledJob("my-task", "*/1 * * * *", myFunc)
    
    // Start application (Leader Election starts automatically)
    ginshared.Start()
}
Enable RAM Mode

Use the ram build tag. This will compile cron_ram.go and exclude Redis dependencies.

go build -tags ram ./...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Deprecated: ScheduleLockerEnabled is deprecated and ignored.
	ScheduleLockerEnabled = true
	JobHistoryEnabled     = true
	ScheduleDisabled      = false
	JobRecoveryEnabled    = true
)
View Source
var JobHistoryAdaptor = core.NewChanAdaptor[JobHistory](1000)

Functions

func CheckIfEnabled added in v0.8.6

func CheckIfEnabled() cron.JobWrapper

func CreateSchedule

func CreateSchedule(jobname, schedule string, cmd func(), opts ...ScheduleOptions) error

func CreateScheduledJob added in v0.11.3

func CreateScheduledJob(jobname, schedule string, cmd func() error, opts ...ScheduleOptions) error

func CreateScheduledJobWithContext added in v0.11.8

func CreateScheduledJobWithContext(jobname, schedule string, cmd func(ctx context.Context) error, opts ...ScheduleOptions) error

func DoCleanup added in v0.8.0

func DoCleanup(settingkey string, tables []string, col string, duration string) interface{}

func InitDBCronJob added in v0.8.0

func InitDBCronJob(logger *zap.Logger, db *gorm.DB) (core.Startup, error)

func InitScheduleCleanupJob added in v0.8.0

func InitScheduleCleanupJob(settingkey string) interface{}

func IsLeader added in v0.12.3

func IsLeader() bool

func List added in v0.10.7

func List() []string

func Run added in v0.10.1

func Run(jobname string) (err error)

func Withhistory added in v0.8.1

func Withhistory(jobname string) cron.JobWrapper

decrepted, will be removed next release.

Types

type CleanupService added in v0.8.0

type CleanupService struct {
	DBMap map[string]*gorm.DB
	// contains filtered or unexported fields
}

func (*CleanupService) Cleanup added in v0.8.0

func (cs *CleanupService) Cleanup(req *DBCleanupReq) error

func (*CleanupService) GetDefaultRequest added in v0.8.0

func (cs *CleanupService) GetDefaultRequest() *DBCleanupReq

func (*CleanupService) RegConnection added in v0.8.0

func (cs *CleanupService) RegConnection(name string, db *gorm.DB)

type DBCleanupReq added in v0.8.0

type DBCleanupReq struct {
	Cnn            string   //connection name
	Tables         []string //tables to be clean
	PrefixIncluded bool     // table names included table prefix
	DeletedField   string   //field name, default is deletedAt
	Duration       string   // only delete DeletedAt <  now - duration
	Batch          int      // batch per deleted
}

type DBCronJob added in v0.8.0

type DBCronJob struct {
	Name     string
	Schedule string
	Sql      []string
	Logger   *zap.Logger
	DB       *gorm.DB
}

func (*DBCronJob) FireJob added in v0.8.0

func (job *DBCronJob) FireJob()

type JobHistory added in v0.8.1

type JobHistory struct {
	App      string
	Job      string
	Start    time.Time
	Finished time.Time
	Duration time.Duration
	Succeed  bool
	Message  string
}

func GetLastDoneJobHistory added in v0.10.6

func GetLastDoneJobHistory(jobname string) *JobHistory

type JobHistoryProvider added in v0.10.6

type JobHistoryProvider struct {
	Bus       EventBus.Bus
	Persister cache.Hash
}

func (*JobHistoryProvider) GetLastDoneJobHistory added in v0.10.6

func (p *JobHistoryProvider) GetLastDoneJobHistory(jobname string) *JobHistory

func (*JobHistoryProvider) SetJobhistory added in v0.10.6

func (p *JobHistoryProvider) SetJobhistory(h JobHistory)

type LeaderElection added in v0.12.3

type LeaderElection struct {
	// contains filtered or unexported fields
}

LeaderElection manages leader election process

func NewLeaderElection added in v0.12.3

func NewLeaderElection(client *redis.Client, logger *zap.Logger, cfg *LeaderElectionConfig) *LeaderElection

NewLeaderElection creates a new LeaderElection instance

func (*LeaderElection) GetCandidateID added in v0.12.3

func (le *LeaderElection) GetCandidateID() string

GetLeaderID returns the candidate ID of this instance

func (*LeaderElection) IsLeader added in v0.12.3

func (le *LeaderElection) IsLeader() bool

IsLeader returns true if the current instance is the leader

func (*LeaderElection) Start added in v0.12.3

func (le *LeaderElection) Start()

Start begins the leader election process in background

func (*LeaderElection) Stop added in v0.12.3

func (le *LeaderElection) Stop()

Stop stops the leader election process

type LeaderElectionConfig added in v0.12.3

type LeaderElectionConfig struct {
	Interval time.Duration `yaml:"interval"`
	TTL      time.Duration `yaml:"ttl"`
	Key      string        `yaml:"key"`
}

LeaderElectionConfig defines configuration for leader election

type ScheduleOptions added in v0.10.18

type ScheduleOptions struct {
	// Deprecated: Nolocker is deprecated and ignored.
	Nolocker  bool
	NoGlobal  bool // ignore ScheduleDisabled
	NoHistory bool
}

type ScheduledJob added in v0.12.3

type ScheduledJob struct {
	Cron     *cron.Cron
	EntryID  cron.EntryID
	Name     string
	Schedule string
	Fn       func()
}

Jump to

Keyboard shortcuts

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