gocron

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 7 Imported by: 0

README

gocron

cron v3基础上封装的定时任务库。


安装

go get -u github.com/zhufuyi/pkg/gocron


使用示例

package main

import (
    "fmt"
    "time"

    "github.com/zhufuyi/pkg/gocron"
)

var task1 = func() {
     fmt.Println("this is task1")
     fmt.Println("running task list:", gocron.GetRunningTasks()) // 当前运行的任务
}

var taskOnce = func() {
	taskName := "taskOnce"
    fmt.Println("this is taskOnce")
    gocron.DeleteTask(taskName)  // 执行完删除任务
}

func main() {
    // 初始化
    err := gocron.Init()
    if err != nil {
        panic(err)
    }

    // 运行定时任务
    gocron.Run([]*gocron.Task{
        {
            Name:     "task1",
            TimeSpec: "@every 2s",
            Fn:       task1,
        },
        {
            Name:     "taskOnce",
            TimeSpec: "@every 5s",
            Fn:       taskOnce,
        },
    }...)

    time.Sleep(time.Minute)

    // 删除任务task1
    gocron.DeleteTask("task1")

    // 查看正在运行的任务
    fmt.Println("running task list:", gocron.GetRunningTasks())
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteTask

func DeleteTask(name string)

DeleteTask 删除任务

func EveryDay

func EveryDay(size int) string

EveryDay 每隔size天执行(1~31)

func EveryHour

func EveryHour(size int) string

EveryHour 每隔size小时执行(1~23)

func EveryMinute

func EveryMinute(size int) string

EveryMinute 每隔size分钟执行(1~59)

func EverySecond

func EverySecond(size int) string

EverySecond 每隔size秒执行(1~59)

func GetRunningTasks

func GetRunningTasks() []string

GetRunningTasks 获取正在运行的任务名称列表

func Init

func Init(opts ...Option) error

Init 初始化和启动定时任务

func IsRunningTask

func IsRunningTask(name string) bool

IsRunningTask 判断任务是运行

func Run

func Run(tasks ...*Task) error

Run 添加新的任务

func Stop

func Stop()

Stop 停止定时任务

Types

type Option

type Option func(*options)

Option set the cron options.

func WithLog

func WithLog(log *zap.Logger) Option

WithLog 设置日志

type Task

type Task struct {
	// 秒(0-59) 分(0-59) 时(0-23) 日(1-31) 月(1-12) 星期(0-6)
	// "*/5 * * * * *"  表示每隔5秒执行
	// "0 15,45 9-12 * * * "  表示每天上午9点到12点的第15和第45分钟执行
	TimeSpec string

	Name string // 任务名称
	Fn   func() // 任务
}

Task 定时任务

Jump to

Keyboard shortcuts

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