queue_go/queue.go

120 lines
2.1 KiB
Go
Raw Normal View History

2017-04-26 06:45:40 +00:00
package queue
import (
"container/heap"
2017-04-26 06:46:04 +00:00
"loafle.com/overflow/agent_api/observer"
2017-04-26 06:58:38 +00:00
"log"
2017-04-26 06:46:04 +00:00
"time"
2017-04-26 06:45:40 +00:00
)
type EventType int
const (
2017-04-26 06:46:04 +00:00
DATA_TYPE EventType = 0
2017-04-26 06:45:40 +00:00
EVENT_TYPE EventType = 1
)
2017-04-26 06:46:04 +00:00
2017-04-26 06:45:40 +00:00
type item struct {
2017-04-26 06:46:04 +00:00
value interface{}
2017-04-26 06:45:40 +00:00
priority int
}
type LoafleQueue struct {
2017-04-26 06:46:04 +00:00
items []*item
2017-04-26 06:45:40 +00:00
queueType string
2017-04-26 06:46:04 +00:00
interval time.Duration
2017-04-26 06:45:40 +00:00
eventChanel chan interface{}
}
func (lq LoafleQueue) Len() int {
return len(lq.items)
}
func (lq LoafleQueue) Less(i, j int) bool {
return lq.items[i].priority < lq.items[j].priority
}
func (lq LoafleQueue) Swap(i, j int) {
lq.items[i], lq.items[j] = lq.items[j], lq.items[i]
}
func (lq *LoafleQueue) GetItems() []*item {
time.Sleep(time.Second * lq.interval)
resultItems := make([]*item, 0)
for lq.Len() > 0 {
item := heap.Pop(lq).(*item)
resultItems = append(resultItems, item)
}
return resultItems
}
func (lq *LoafleQueue) Push(i interface{}) {
n := len(lq.items)
nItem := i.(*item)
nItem.priority = n
lq.items = append(lq.items, nItem)
}
func (lq *LoafleQueue) Pop() interface{} {
old := lq.items
n := len(old)
nItem := old[n-1]
lq.items = old[0 : n-1]
return nItem
}
func (lq LoafleQueue) newItem(value interface{}) *item {
return &item{
2017-04-26 06:46:04 +00:00
value: value,
2017-04-26 06:45:40 +00:00
}
}
func (lq *LoafleQueue) notifyEventHandler(c chan interface{}) {
for data := range c {
it := lq.newItem(data)
heap.Push(lq, it)
}
}
2017-04-26 06:58:38 +00:00
func (lq *LoafleQueue) StringType(tp EventType) string {
var tempType string
if tp == DATA_TYPE {
tempType = "DATA_TYPE"
} else if tp == EVENT_TYPE {
tempType = "EVENT_TYPE"
} else {
log.Fatal("Event Type Error")
}
return tempType
}
2017-04-26 06:45:40 +00:00
func (lq *LoafleQueue) Close() {
if lq.eventChanel != nil {
observer.Remove(lq.queueType, lq.eventChanel)
}
}
func NewLoafleQueue(eventType EventType, interval time.Duration) *LoafleQueue {
items := make([]*item, 0)
2017-04-26 06:46:04 +00:00
event := make(chan interface{}, 0)
2017-04-26 06:45:40 +00:00
lq := &LoafleQueue{
2017-04-26 06:58:38 +00:00
items: items,
//queueType: tempType,
2017-04-26 06:46:04 +00:00
interval: interval,
eventChanel: event,
2017-04-26 06:45:40 +00:00
}
2017-04-26 06:58:38 +00:00
lq.queueType = lq.StringType(eventType)
heap.Init(lq)
2017-04-26 06:45:40 +00:00
observer.Add(lq.queueType, lq.eventChanel)
go lq.notifyEventHandler(event)
return lq
}