package lightCore import ( "fmt" "sync" ) type TaskFunc func() var taskList chan *TaskExecutor //任务列表 var once sync.Once func getTaskList() chan *TaskExecutor { once.Do(func() { taskList = make(chan *TaskExecutor, 0) }) return taskList } func init() { chList := getTaskList() //得到任务列表 go func() { for t := range chList { doTask(t) } }() } func doTask(t *TaskExecutor) { go func() { defer func() { if t.callback != nil { t.callback() } }() t.Exec() }() } type TaskExecutor struct { f TaskFunc callback func() } func NewTaskExecutor(f TaskFunc, callback func()) *TaskExecutor { return &TaskExecutor{f: f, callback: callback} } func (t *TaskExecutor) Exec() { t.f() } func Task(f TaskFunc, callBack func()) { if f == nil { return } newF := func() { defer func() { if e := recover(); e != nil { if err, ok := e.(string); ok { fmt.Println("===================================") fmt.Println(fmt.Sprintf("协程运行错误:%s", err)) fmt.Println("===================================") } else { fmt.Println("===================================") fmt.Println(fmt.Sprintf("协程运行错误:%s", "未知")) fmt.Println("===================================") } } }() f() } go func() { getTaskList() <- NewTaskExecutor(newF, callBack) //添加任务队列 }() }