2016-04-04 15:44:34 +02:00
|
|
|
package tasks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2016-04-07 14:49:34 +02:00
|
|
|
"time"
|
2016-04-04 15:44:34 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type taskPool struct {
|
2016-04-07 14:49:34 +02:00
|
|
|
queue []*task
|
|
|
|
register chan *task
|
|
|
|
running *task
|
2016-04-04 15:44:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var pool = taskPool{
|
2016-04-07 14:49:34 +02:00
|
|
|
queue: make([]*task, 0),
|
|
|
|
register: make(chan *task),
|
|
|
|
running: nil,
|
2016-04-04 15:44:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *taskPool) run() {
|
2016-04-07 14:49:34 +02:00
|
|
|
ticker := time.NewTicker(10 * time.Second)
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
ticker.Stop()
|
|
|
|
}()
|
|
|
|
|
2016-04-04 15:44:34 +02:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case task := <-p.register:
|
2016-04-07 14:49:34 +02:00
|
|
|
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)
|
2016-04-07 14:49:34 +02:00
|
|
|
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()
|
|
|
|
}
|