Semaphore/api/tasks/pool.go

52 lines
716 B
Go
Raw Normal View History

2016-04-04 15:44:34 +02:00
package tasks
import (
"fmt"
"time"
2016-04-04 15:44:34 +02:00
)
type taskPool struct {
queue []*task
register chan *task
running *task
2016-04-04 15:44:34 +02:00
}
var pool = taskPool{
queue: make([]*task, 0),
register: make(chan *task),
running: nil,
2016-04-04 15:44:34 +02:00
}
func (p *taskPool) run() {
ticker := time.NewTicker(10 * time.Second)
defer func() {
ticker.Stop()
}()
2016-04-04 15:44:34 +02:00
for {
select {
case task := <-p.register:
fmt.Println(task)
if p.running == nil {
go task.run()
2016-04-04 15:44:34 +02:00
continue
}
p.queue = append(p.queue, task)
case <-ticker.C:
if len(p.queue) == 0 || p.running != nil {
continue
}
fmt.Println("Running a task.")
go pool.queue[0].run()
pool.queue = pool.queue[1:]
2016-04-04 15:44:34 +02:00
}
}
}
func StartRunner() {
pool.run()
}