68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
|
|
package entities
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"time"
|
|||
|
|
|
|||
|
|
"github.com/google/uuid"
|
|||
|
|
"gorm.io/gorm"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// TaskStatus 任务状态
|
|||
|
|
type TaskStatus string
|
|||
|
|
|
|||
|
|
const (
|
|||
|
|
TaskStatusPending TaskStatus = "pending"
|
|||
|
|
TaskStatusRunning TaskStatus = "running"
|
|||
|
|
TaskStatusCompleted TaskStatus = "completed"
|
|||
|
|
TaskStatusFailed TaskStatus = "failed"
|
|||
|
|
TaskStatusCancelled TaskStatus = "cancelled"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// AsyncTask 异步任务实体
|
|||
|
|
type AsyncTask struct {
|
|||
|
|
ID string `gorm:"type:char(36);primaryKey"`
|
|||
|
|
Type string `gorm:"not null;index"`
|
|||
|
|
Payload string `gorm:"type:text"`
|
|||
|
|
Status TaskStatus `gorm:"not null;index"`
|
|||
|
|
ScheduledAt *time.Time `gorm:"index"`
|
|||
|
|
StartedAt *time.Time
|
|||
|
|
CompletedAt *time.Time
|
|||
|
|
ErrorMsg string
|
|||
|
|
RetryCount int `gorm:"default:0"`
|
|||
|
|
MaxRetries int `gorm:"default:5"`
|
|||
|
|
CreatedAt time.Time
|
|||
|
|
UpdatedAt time.Time
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// TableName 指定表名
|
|||
|
|
func (AsyncTask) TableName() string {
|
|||
|
|
return "async_tasks"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// BeforeCreate GORM钩子,在创建前生成UUID
|
|||
|
|
func (t *AsyncTask) BeforeCreate(tx *gorm.DB) error {
|
|||
|
|
if t.ID == "" {
|
|||
|
|
t.ID = uuid.New().String()
|
|||
|
|
}
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// IsCompleted 检查任务是否已完成
|
|||
|
|
func (t *AsyncTask) IsCompleted() bool {
|
|||
|
|
return t.Status == TaskStatusCompleted
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// IsFailed 检查任务是否失败
|
|||
|
|
func (t *AsyncTask) IsFailed() bool {
|
|||
|
|
return t.Status == TaskStatusFailed
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// IsCancelled 检查任务是否已取消
|
|||
|
|
func (t *AsyncTask) IsCancelled() bool {
|
|||
|
|
return t.Status == TaskStatusCancelled
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// CanRetry 检查任务是否可以重试
|
|||
|
|
func (t *AsyncTask) CanRetry() bool {
|
|||
|
|
return t.Status == TaskStatusFailed && t.RetryCount < t.MaxRetries
|
|||
|
|
}
|