task

package
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 7 Imported by: 3

Documentation

Overview

Package task 提供全局任务调度池与任务组,基于 ants 协程池实现并发控制、错误聚合与优雅降级

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add added in v2.6.0

func Add(task func())

Add 执行任务 任务优先提交至全局任务池,池满或不可用时降级为直接创建协程执行 @param task func() 待执行的任务

func AddTask

func AddTask(task func())

AddTask 添加任务 Deprecated: As of due v2.6.0+, this function simply calls Add. @param task func() 待执行的任务

func NewPool

func NewPool(opts ...Option) *defaultPool

NewPool 新建任务池 根据配置创建 ants 协程池,支持设置池大小、非阻塞与禁用清理等特性 @param opts ...Option 可选配置项 @return @1 *defaultPool 任务池实例

func Release

func Release()

Release 释放全局任务池

func SetPool

func SetPool(pool Pool)

SetPool 设置全局任务池 替换前会释放旧任务池 @param pool Pool 任务池

Types

type Group added in v2.6.0

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

Group 任务组 聚合多个任务的错误,支持上下文取消与并发数限制

func WithContext added in v2.6.0

func WithContext(ctx context.Context) (*Group, context.Context)

WithContext 创建一个新的任务组,与上下文关联 首个任务出错或 Wait 返回时,会以该错误作为原因取消上下文 @param ctx context.Context 父上下文 @return @1 *Group 任务组 @return @2 context.Context 派生上下文

func (*Group) Go added in v2.6.0

func (g *Group) Go(f func() error)

Go 执行任务 在全局任务池中执行,受并发数限制;任务出错时记录首个错误并取消上下文 @param f func() error 待执行的任务

func (*Group) SetLimit added in v2.6.0

func (g *Group) SetLimit(n int)

SetLimit 设置并发限制 并发数需在任务启动前设置;设置为负数表示不限制并发;已有任务运行时修改会触发 panic @param n int 最大并发数

func (*Group) TryGo added in v2.6.0

func (g *Group) TryGo(f func() error) bool

TryGo 尝试执行任务 并发数未满时立即执行并返回 true,否则返回 false @param f func() error 待执行的任务 @return @1 bool 是否成功启动任务

func (*Group) Wait added in v2.6.0

func (g *Group) Wait() error

Wait 等待所有任务完成 返回首个任务产生的错误,并取消派生上下文 @return @1 error 首个任务错误,无错误时返回 nil

type Option

type Option func(o *options)

Option 任务池配置项

func WithDisablePurge

func WithDisablePurge(disablePurge bool) Option

WithDisablePurge 设置是否禁用清除 禁用后空闲协程不会被定期回收 @param disablePurge bool 是否禁用清除 @return @1 Option 配置项

func WithNonblocking

func WithNonblocking(nonblocking bool) Option

WithNonblocking 设置是否非阻塞 非阻塞模式下池满时任务提交立即返回错误,而非阻塞等待 @param nonblocking bool 是否非阻塞 @return @1 Option 配置项

func WithSize

func WithSize(size int) Option

WithSize 设置任务池大小 @param size int 任务池大小 @return @1 Option 配置项

type Pool

type Pool interface {
	// AddTask 添加任务
	// @param task func() 待执行的任务
	// @return @1 error 错误信息
	AddTask(task func()) error
	// Release 释放任务池
	Release()
}

Pool 任务池接口

func GetPool

func GetPool() Pool

GetPool 获取全局任务池 @return @1 Pool 任务池

Jump to

Keyboard shortcuts

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