- 用SyncMapWithTimeout管理tasksch任务

This commit is contained in:
gazebo
2019-08-07 14:55:54 +08:00
parent 8768fe8236
commit f06456cec1
3 changed files with 40 additions and 34 deletions

View File

@@ -2,45 +2,44 @@ package tasksch
import (
"sort"
"sync"
"time"
"git.rosy.net.cn/jx-callback/business/jxutils"
)
var (
defTaskMan TaskMan
defLastHours = 24
maxStoreTime = 48 * time.Hour // 最多存两天时间
)
type TaskMan struct {
taskList map[string]ITask
locker sync.RWMutex
taskMap jxutils.SyncMapWithTimeout
}
func init() {
defTaskMan.taskList = make(map[string]ITask)
}
func (m *TaskMan) GetTasks(taskID string, fromStatus, toStatus int, lastHours int, createdBy string) (taskList TaskList) {
m.locker.RLock()
defer m.locker.RUnlock()
if lastHours == 0 {
lastHours = defLastHours
}
lastTime := time.Now().Add(time.Duration(-lastHours) * time.Hour).Unix()
for k, v := range m.taskList {
m.taskMap.Range(func(key, value interface{}) bool {
k := key.(string)
v := value.(ITask)
status := v.GetStatus()
if !((createdBy != "" && createdBy != v.GetCreatedBy()) || (taskID != "" && taskID != k) || status < fromStatus || status > toStatus || v.GetCreatedAt().Unix() < lastTime) {
taskList = append(taskList, v)
}
}
return true
})
sort.Sort(TaskList(taskList))
return taskList
}
func (m *TaskMan) ManageTask(task ITask) ITask {
m.locker.Lock()
defer m.locker.Unlock()
m.taskList[task.GetID()] = task
m.taskMap.StoreWithTimeout(task.GetID(), task, maxStoreTime)
return task
}
@@ -53,7 +52,7 @@ func ManageTask(task ITask) ITask {
}
func IsTaskRunning(taskID string) bool {
if taskList := GetTasks(taskID, TaskStatusBegin, TaskStatusWorking, 36, ""); len(taskList) > 0 {
if taskList := GetTasks(taskID, TaskStatusBegin, TaskStatusWorking, 0, ""); len(taskList) > 0 {
return true
}
return false