init
This commit is contained in:
62
task/task.go
Normal file
62
task/task.go
Normal file
@ -0,0 +1,62 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"Edu/utils"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ITask interface {
|
||||
MarshalBinary() ([]byte, error)
|
||||
UnmarshalBinary(data []byte) error
|
||||
Handle() error
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
ID string `json:"id"` // Job唯一标识
|
||||
Topic string `json:"topic"` // Job类型
|
||||
Delay int64 `json:"delay"` // Job需要延迟的时间, 单位:秒
|
||||
Body ITask `json:"body"` // Job的内容,供消费者做具体的业务处理
|
||||
}
|
||||
|
||||
type TaskHandle func(topic string, delay int64, body ITask) *Task
|
||||
|
||||
func (this *Task) MarshalBinary() ([]byte, error) {
|
||||
return json.Marshal(this)
|
||||
}
|
||||
|
||||
func (this *Task) UnmarshalBinary(data []byte) error {
|
||||
return utils.FromJSONBytes(data, this)
|
||||
}
|
||||
|
||||
func (this *Task) setID() string {
|
||||
return utils.Sha1String(fmt.Sprintf("%s%d%s", this.Topic, time.Now().UnixNano(), utils.GetRandomCode(6)))
|
||||
}
|
||||
|
||||
func (this *Task) DelayUnix() int64 {
|
||||
return time.Now().Unix() + this.Delay
|
||||
}
|
||||
|
||||
func (this *Task) Push() {
|
||||
TaskListenEvent.Join(this)
|
||||
}
|
||||
|
||||
// Consume 消费
|
||||
func (this *Task) Consume() {
|
||||
TaskListenEvent.Quit(this)
|
||||
}
|
||||
|
||||
func (this *Task) Handle() error {
|
||||
// 处理各种方法
|
||||
this.Body.(*Order).Handle()
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewTask() TaskHandle {
|
||||
return func(topic string, delay int64, body ITask) *Task {
|
||||
task := &Task{Topic: topic, Delay: delay, Body: body}
|
||||
task.ID = task.setID()
|
||||
return task
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user