Skip to content

Introduction

Task queue module, providing asynchronous task addition, deduplication, execution, and timed loop functionality. Tasks are executed sequentially in queue order (single-thread model), supporting timeout control and unique task constraints (the same action can only exist once in the queue). Suitable for background asynchronous operations, timed polling, and similar scenarios.

Import

go
import "github.com/wallace5303/ee-go/etask"

API

Task

Description: Task struct, representing an asynchronous task in the queue.

FieldTypeDescription
ActionstringTask identifier name, e.g. "task.demo"
Handlerreflect.ValueTask handler function, wrapped via reflect.ValueOf
Args[]interface{}Argument list passed to Handler
Createdtime.TimeTask creation time
Timeouttime.DurationTask execution timeout duration, default 24 hours

UniqueActions

Description: Global unique task action list. For task actions in this list, only one instance can exist in the queue — if the current queue or executing task already has the same action, AddTask / AddTaskWithTimeout will skip the addition.

Type: []string

Example:

go
etask.UniqueActions = []string{"task.syncData", "task.cleanup"}
// Adding a task with the same name later will be automatically skipped if it already exists in the queue

AddTask(action, handler, args...)

Description: Add a task to the queue. Default timeout is 24 hours (24 * time.Hour). If the application is exiting (eruntime.IsExiting == true), the addition is skipped. If the task action belongs to UniqueActions and a task with the same name already exists in the queue, the addition is skipped.

Parameters:

ParameterTypeRequiredDescription
actionstringYesTask identifier name, e.g. "task.demo"
handlerinterface{}YesTask handler function
args...interface{}NoArguments passed to handler

Returns: No return value

Example:

go
etask.AddTask("task.sendEmail", func(to string) {
    fmt.Println("sending email to:", to)
}, "user@example.com")

See also: AddTaskWithTimeout — Add a task with custom timeout

AddTaskWithTimeout(action, handler, timeout, args...)

Description: Add a task with custom timeout to the queue. When timeout occurs, the task is marked with a warning in the log but the goroutine is not terminated. Otherwise same logic as AddTask.

Parameters:

ParameterTypeRequiredDescription
actionstringYesTask identifier name
handlerinterface{}YesTask handler function
timeouttime.DurationYesTask execution timeout duration
args...interface{}NoArguments passed to handler

Returns: No return value

Example:

go
etask.AddTaskWithTimeout("task.longOperation", func() {
    // Time-consuming operation
}, 5*time.Minute)

Contain(action, moreActions...)

Description: Check whether the queue contains a task with the specified action. Can check multiple actions at once (deduplicated check), returns true if any match exists in the queue.

Parameters:

ParameterTypeRequiredDescription
actionstringYesTask action to check
moreActions...stringNoAdditional action list to check

Returns: booltrue if a task with matching action exists in the queue, false otherwise

Example:

go
if etask.Contain("task.syncData", "task.cleanup") {
    fmt.Println("queue contains syncData or cleanup task")
}

Status()

Description: Print current task queue status information. Outputs the action list and count of all pending tasks and the currently executing task. Only outputs to logs in development environment (eruntime.IsDev()).

Returns: No return value

Example:

go
etask.Status()
// Log output in development environment:
// task status data:  [{"action":"task.syncData"}, {"action":"task.sendEmail"}]

ExecTask()

Description: Take a task from the queue head and execute it. If the application is exiting (eruntime.IsExiting == true) or the queue is empty, returns directly. When executing a task, uses reflect.Value.Call to invoke the handler and controls timeout via context.WithTimeout. On task completion, logs "task [action] done", on timeout logs "task [action] timeout". If a panic occurs during execution, it is captured and logged by eutil.Recover().

Returns: No return value

Example:

go
// Typically called in the main loop
for {
    etask.ExecTask()
    time.Sleep(100 * time.Millisecond)
}

Every(interval, f)

Description: Execute a function repeatedly at a specified time interval. Randomly sleeps 50~200 milliseconds at startup (to avoid multiple instances starting simultaneously), then loops indefinitely: execute function → wait interval → execute again. Panics during function execution are captured by eutil.Recover() and do not interrupt the loop.

Parameters:

ParameterTypeRequiredDescription
intervaltime.DurationYesLoop interval duration
ffunc()YesFunction to execute on each loop iteration

Returns: No return value (this function loops indefinitely, typically called in a separate goroutine)

Example:

go
// Start a timed task in a separate goroutine
go etask.Every(30*time.Second, func() {
    fmt.Println("health check running")
})