# command **Repository Path**: xgo-core/command ## Basic Information - **Project Name**: command - **Description**: command - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-07-17 - **Last Updated**: 2026-07-17 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # XGo Command `gitee.com/xgo-core/command` 用于执行注册在 XGo container 中的命令任务。一个命令可以在启动时立即执行,也可以按 cron 定时执行,或两者同时启用。 ## 安装 ```go import "gitee.com/xgo-core/command" ``` ## 命令接口 ```go type CommandInterface interface { Cron() command.Cron Handle(ctx *xgocontext.XGoContext) error } ``` `Handle` 会收到本次执行专属的 `XGoContext`。该 context 携带链路追踪信息,并会在调用 `command.Close()` 时被取消。 ## 执行配置 ```go type Cron struct { Immediate bool Schedule string Times int } ``` - `Immediate`: `command.New(ctx)` 加载命令时立即执行一次。 - `Schedule`: robfig/cron v3 表达式。为空表示不定时执行。 - `Times`: 定时执行次数上限。`0` 表示不限次数。立即执行不计入该次数。 `Schedule` 使用 `github.com/robfig/cron/v3`,支持 `@hourly`、`@every 1m` 等描述符。 ## 使用方式 ```go package jobs import ( commandpkg "gitee.com/xgo-core/command" "gitee.com/xgo-core/container" xgocontext "gitee.com/xgo-core/context" ) type SyncUserJob struct{} func (j *SyncUserJob) Cron() commandpkg.Cron { return commandpkg.Cron{ Immediate: true, Schedule: "@every 5m", Times: 0, } } func (j *SyncUserJob) Handle(ctx *xgocontext.XGoContext) error { // 如果调用下游接口,尽量传递 ctx.Context()。 return nil } func init() { container.MustInjectAs[commandpkg.CommandInterface](&SyncUserJob{}) } ``` 启动和关闭: ```go ctx := xgocontext.New() command.New(ctx) defer command.Close() ``` ## 关闭语义 `Close` 会停止所有定时器,取消所有正在执行的命令 context,并等待已经开始的 `Handle` 返回。 Go 无法强制停止 goroutine。长时间运行的命令需要主动监听 `ctx.Done()`,或把 `ctx.Context()` 传给阻塞的下游调用: ```go select { case <-ctx.Done(): return ctx.Err() default: } ``` ## 链路追踪与日志 每次执行都会创建一个 `command.handle` span,包含: - `command.component`: 命令的具体类型。 - `command.trigger`: `immediate`、`schedule` 或内部测试/自定义触发来源。 执行成功时 span 状态为 `Ok`。执行失败时会把错误记录到 span,通过 `xlog` 输出 panic 日志,并中断进程。