time_wheel

package module
v0.0.0-...-0c15647 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2025 License: MIT Imports: 6 Imported by: 0

README

time_wheel

示例图片

Go语言实现的一个简单时间轮,用于管理和调度单次任务、间隔周期任务、秒级的cron表达式的定时任务。

功能

  • 支持单次延时任务
  • 支持间隔任务 如每5秒执行一次
  • 支持cron表达式任务 如每分钟执行一次
  • 支持时区设置

开始

安装依赖
go get -u github.com/GalaxyFall/time_wheel

单次示例

package main

import "github.com/GalaxyFall/time_wheel"

    tWheel := time_wheel.NewTimeWheel(5, time.Second)

    testfunc := func() {
	//do something
    }

    tWheel.AddTask("test after 1s", time_wheel.WrapperTask(testfunc), time.Now().Add(time.Second))
    tWheel.AddTask("test after 3s", time_wheel.WrapperTask(testfunc), time.Now().Add(time.Second*3))

    tWheel.Start()
    <-time.After(6 * time.Second)

间隔示例

package main

import "github.com/GalaxyFall/time_wheel"

    tWheel := time_wheel.NewTimeWheel(5, time.Second)

    testfunc := func() {
	//do something
    }

    tWheel.AddPeriodicTask("test 2s", time_wheel.WrapperTask(testfunc), time.Second*2)

    tWheel.Start()
    <-time.After(10 * time.Second)

cron示例

package main

import "github.com/GalaxyFall/time_wheel"

    tWheel := time_wheel.NewTimeWheel(5, time.Second)

    testfunc := func() {
	//do something
    }

    tWheel.AddCronTask("test 5s", "*/5 * * * * *", time_wheel.WrapperTask(testfunc))

    tWheel.Start()
    <-time.After(15 * time.Second)
许可证

本项目采用 MIT 许可证。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Log

type Log interface {
	Logf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

type Option

type Option func(*timeWheel)

func WithLocation

func WithLocation(loc *time.Location) Option

func WithLogger

func WithLogger(log Log) Option

func WithTimeFunc

func WithTimeFunc(f func() time.Time) Option

type Task

type Task interface {
	Run()
}

func WrapperTask

func WrapperTask(fn func()) Task

WrapperTask: 包装任务

type TimeWheeler

type TimeWheeler interface {
	Start()
	//Stop:停止时间轮将会移除全部任务
	Stop()
	IsRunning() bool

	AddTask(key string, f Task, execTime time.Time)
	AddPeriodicTask(key string, f Task, Period time.Duration)
	AddCronTask(key string, spec string, f Task) error
	RemoveTask(key string)
}

func NewTimeWheel

func NewTimeWheel(slotSize int, interval time.Duration, opts ...Option) TimeWheeler

Jump to

Keyboard shortcuts

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