Created
July 27, 2021 21:00
-
-
Save Mindgamesnl/5960405772229155df7962d5dafbb4e8 to your computer and use it in GitHub Desktop.
Stupidly simple task manager to schedule concurrent tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package task | |
import "sync" | |
type TaskManager struct { | |
taskQueueLock sync.Mutex | |
taskQueue []func() | |
runningTasks int | |
maxConcurrentTasks int | |
} | |
func NewTaskManager(maxConcurrentTasks int) *TaskManager { | |
return &TaskManager{ | |
taskQueue: []func(){}, | |
runningTasks: 0, | |
maxConcurrentTasks: 0, | |
} | |
} | |
func (tm *TaskManager) AddTask(task func()) { | |
tm.taskQueueLock.Lock() | |
tm.taskQueue = append(tm.taskQueue, task) | |
tm.taskQueueLock.Unlock() | |
go tm.tick() | |
} | |
func (tm *TaskManager) tick() { | |
if tm.runningTasks >= tm.maxConcurrentTasks { | |
// cancel if there's already a reached max of concurrent tasks | |
return | |
} | |
tm.taskQueueLock.Lock() | |
if len(tm.taskQueue) == 0 { | |
// don't do anything, queue is empty | |
tm.taskQueueLock.Unlock() | |
return | |
} | |
// get the first task | |
var task = tm.taskQueue[0] | |
// pull the task so that it can't be done again | |
tm.taskQueue = removeIndex(tm.taskQueue, 0) | |
// run the task, and tick again | |
tm.runningTasks++ | |
tm.taskQueueLock.Unlock() | |
go func() { | |
task() | |
tm.runningTasks-- | |
// tick again | |
tm.tick() | |
}() | |
go tm.tick() | |
} | |
func removeIndex(s []func(), index int) []func() { | |
ret := make([]func(), 0) | |
ret = append(ret, s[:index]...) | |
return append(ret, s[index+1:]...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment