Files
2021-09-28 11:47:19 +08:00

63 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package task
import (
"SciencesServer/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
}
}