CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-go-co-op-gocron-v2

A Golang job scheduling library that lets you run Go functions at pre-determined intervals using cron expressions, fixed durations, daily, weekly, monthly, or one-time schedules with support for distributed deployments.

Overview
Eval results
Files

managing-jobs.mddocs/api/scheduler/

Managing Jobs

How to register, update, remove, and list jobs.

NewJob

NewJob(JobDefinition, Task, ...JobOption) (Job, error)

Registers a new job. Returns the job instance or an error if invalid.

Parameters:

  • JobDefinition: When to run (DurationJob, CronJob, etc.) - see Job Definitions
  • Task: What to run (created with NewTask) - see Tasks
  • JobOption: How to configure (WithName, WithTags, etc.) - see Job Options

Errors:

  • ErrNewJobTaskNil: Task is nil
  • ErrNewJobTaskNotFunc: Task.Function is not a function
  • ErrNewJobWrongNumberOfParameters: Parameter count mismatch
  • ErrNewJobWrongTypeOfParameters: Parameter type mismatch
  • Job definition errors: See specific job types in Job Definitions
  • Job option errors: See Job Options
j, err := s.NewJob(
    gocron.DurationJob(5*time.Minute),
    gocron.NewTask(func() { doWork() }),
    gocron.WithName("my-job"),
    gocron.WithTags("worker"),
)

Update

Update(uuid.UUID, JobDefinition, Task, ...JobOption) (Job, error)

Updates an existing job identified by UUID. Preserves the job ID but replaces all other configuration.

Parameters: Same as NewJob, plus job UUID

Errors: Same as NewJob, plus:

  • ErrJobNotFound: Job with given UUID doesn't exist
// Update job interval
j, err = s.Update(
    j.ID(),
    gocron.DurationJob(10*time.Minute), // new interval
    gocron.NewTask(myFunc),
    gocron.WithName("my-updated-job"),
)

RemoveJob

RemoveJob(uuid.UUID) error

Removes a job by UUID. Returns ErrJobNotFound if job doesn't exist.

err := s.RemoveJob(j.ID())

RemoveByTags

RemoveByTags(...string)

Removes all jobs that have all the specified tags. Does not return an error if no jobs match.

// Remove all jobs tagged "cleanup"
s.RemoveByTags("cleanup")

// Remove jobs tagged with both "worker" AND "low-priority"
s.RemoveByTags("worker", "low-priority")

Jobs

Jobs() []Job

Returns all registered jobs, sorted by job ID.

allJobs := s.Jobs()
for _, j := range allJobs {
    fmt.Printf("Job %s: next run at %v\n", j.Name(), j.NextRun())
}

Job Interface

The Job interface returned by NewJob and Update provides:

type Job interface {
    ID() uuid.UUID
    Name() string
    Tags() []string
    LastRun() (time.Time, error)
    NextRun() (time.Time, error)
    NextRuns(count int) ([]time.Time, error)
    RunNow() error
}

ID

ID() uuid.UUID

Returns the job's unique identifier. The ID is stable across updates.

id := j.ID()

Name

Name() string

Returns the job's name (set via WithName or defaults to qualified function name).

name := j.Name()

Tags

Tags() []string

Returns all tags assigned to the job.

tags := j.Tags()

LastRun

LastRun() (time.Time, error)

Returns the time of the most recent execution. Returns ErrJobNotFound if the job has been removed.

lastRun, err := j.LastRun()
if err != nil {
    log.Printf("Error: %v", err)
}

NextRun

NextRun() (time.Time, error)

Returns the next scheduled execution time. Returns ErrJobNotFound if the job has been removed.

nextRun, err := j.NextRun()
if err != nil {
    log.Printf("Error: %v", err)
}

NextRuns

NextRuns(count int) ([]time.Time, error)

Returns the next count scheduled execution times. Returns ErrJobNotFound if the job has been removed.

nextFive, err := j.NextRuns(5)
if err != nil {
    log.Printf("Error: %v", err)
}
for i, t := range nextFive {
    fmt.Printf("Run %d: %v\n", i+1, t)
}

RunNow

RunNow() error

Triggers an immediate execution without affecting the regular schedule. Returns ErrJobRunNowFailed if the scheduler is unreachable.

err := j.RunNow()
if err != nil {
    log.Printf("Failed to trigger job: %v", err)
}

Usage Examples

Dynamic Job Management

// Add job
j, _ := s.NewJob(
    gocron.DurationJob(5*time.Minute),
    gocron.NewTask(myFunc),
    gocron.WithName("my-job"),
)

// Update job
j, _ = s.Update(
    j.ID(),
    gocron.DurationJob(10*time.Minute),
    gocron.NewTask(myFunc),
    gocron.WithName("my-updated-job"),
)

// Remove specific job
s.RemoveJob(j.ID())

// Remove by tag
s.RemoveByTags("maintenance")

// List all jobs
for _, job := range s.Jobs() {
    fmt.Println(job.Name())
}

Inspecting Job Status

j, _ := s.NewJob(
    gocron.DurationJob(time.Minute),
    gocron.NewTask(myFunc),
    gocron.WithName("status-check"),
)

// Get job info
id := j.ID()
name := j.Name()
tags := j.Tags()

// Check execution times
lastRun, err := j.LastRun()
if err == nil {
    fmt.Printf("Last ran at: %v\n", lastRun)
}

nextRun, err := j.NextRun()
if err == nil {
    fmt.Printf("Next run at: %v\n", nextRun)
}

// Get future schedule
nextFive, _ := j.NextRuns(5)
for i, t := range nextFive {
    fmt.Printf("Scheduled run %d: %v\n", i+1, t)
}

Trigger Manual Execution

j, _ := s.NewJob(
    gocron.DailyJob(1, gocron.NewAtTimes(
        gocron.NewAtTime(9, 0, 0),
    )),
    gocron.NewTask(dailyReport),
    gocron.WithName("daily-report"),
)

// Run report on-demand (doesn't affect daily 9 AM schedule)
err := j.RunNow()
if err != nil {
    log.Printf("Failed to run report: %v", err)
}

See Also

Install with Tessl CLI

npx tessl i tessl/golang-github-com-go-co-op-gocron-v2

docs

api

errors.md

quick-reference.md

tasks.md

index.md

tile.json