collector_go/scheduler/scheduler.go

66 lines
1.2 KiB
Go
Raw Normal View History

2017-04-14 10:09:51 +00:00
package scheduler
import (
c "loafle.com/overflow/crawler_go"
2017-04-25 03:14:15 +00:00
"loafle.com/overflow/cron_go"
2017-04-14 10:09:51 +00:00
"log"
"strconv"
"sync"
)
const DEFAULT_INTERVAL = 5
type Scheduler struct {
2017-04-15 11:32:56 +00:00
crawler *c.CrawlerImpl
once sync.Once
cronChan chan bool
2017-04-14 10:09:51 +00:00
}
func (s *Scheduler) Init() {
s.once.Do(func() {
2017-04-15 11:32:56 +00:00
s.cronChan = cron.Start()
2017-04-14 10:09:51 +00:00
s.crawler = &c.CrawlerImpl{}
})
}
2017-04-15 11:32:56 +00:00
func (s *Scheduler) Stop() {
s.cronChan <- false
}
func (s *Scheduler) NewSchedule(id, interval string, fn interface{}) error {
return s.newSchedule(id, interval, fn)
2017-04-14 10:09:51 +00:00
}
2017-04-15 11:32:56 +00:00
func (s *Scheduler) RemoveSchedule(id string) error {
return cron.Remove(id)
2017-04-14 10:09:51 +00:00
}
2017-04-15 11:32:56 +00:00
func (s *Scheduler) RemoveAllSchedule() error {
return cron.RemoveAll()
2017-04-14 10:09:51 +00:00
}
func (s *Scheduler) UpdateSchedule(id string, interval string) {
i, err := strconv.Atoi(interval)
if err != nil {
i = DEFAULT_INTERVAL
}
2017-04-17 08:20:21 +00:00
cron.UpdateTask(id, uint64(i))
2017-04-14 10:09:51 +00:00
}
2017-04-15 11:32:56 +00:00
func (s *Scheduler) newSchedule(id string, interval string, fn interface{}) error {
i, err := strconv.Atoi(interval)
if err != nil {
i = DEFAULT_INTERVAL
}
2017-04-17 08:20:21 +00:00
return cron.AddTask(id, uint64(i)).Invoke(fn, id)
2017-04-15 11:32:56 +00:00
}
2017-04-14 10:09:51 +00:00
func (s *Scheduler) requestGet(id string) {
data, err := s.crawler.Get(id)
if err != nil {
log.Printf("[ID: %s] An error has occurred. %s", id, err.Error())
return
}
log.Println(data)
}