v1.2.1

Getting Started

Last updated

This page covers installing go-scheduler, creating a scheduler, registering a first task, and shutting down gracefully.

Prerequisites

Installation

Using go get

go get github.com/pardnchiu/go-scheduler@latest

The package lives in the core subdirectory:

import "github.com/pardnchiu/go-scheduler/core"

From Source

git clone https://github.com/pardnchiu/go-scheduler.git
cd go-scheduler
go build ./...
go test -race ./...

First Task

package main

import (
    "context"
    "log"
    "os/signal"
    "syscall"

    "github.com/pardnchiu/go-scheduler/core"
)

func main() {
    c, err := core.New(core.Config{})
    if err != nil {
        log.Fatal(err)
    }

    id, err := c.Add("@every 30s", func() {
        log.Println("heartbeat")
    }, "heartbeat")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("task id:", id)

    c.Start()

    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()
    <-ctx.Done()

    // wait for in-flight tasks
    <-c.Stop().Done()
}
Step Call Result
1 core.New(core.Config{}) Creates a scheduler in time.Local
2 c.Add("@every 30s", ...) Registers the task and returns an increasing ID; @every has a 30-second minimum
3 c.Start() Computes each task's next fire time and starts the event loop
4 c.Stop().Done() Stops scheduling; the context is cancelled once in-flight tasks finish

Next Steps

中文