Files
cgrates/cmd/cgr-rater/scheduler.go
2012-08-25 10:02:33 +03:00

96 lines
2.5 KiB
Go

/*
Rating system designed to be used in VoIP Carriers World
Copyright (C) 2012 Radu Ioan Fericean
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package main
import (
"fmt"
"github.com/cgrates/cgrates/timespans"
"sort"
"time"
)
var (
sched = new(scheduler)
timer *time.Timer
restartLoop = make(chan byte)
)
type scheduler struct {
queue timespans.ActionTimingPriotityList
}
func (s scheduler) loop() {
for {
if len(s.queue) == 0 {
<-restartLoop
}
a0 := s.queue[0]
now := time.Now()
if a0.GetNextStartTime().Equal(now) || a0.GetNextStartTime().Before(now) {
timespans.Logger.Debug(fmt.Sprintf("%v - %v", a0.Tag, a0.Timing))
go a0.Execute()
sched.queue = append(s.queue, a0)
sched.queue = s.queue[1:]
sort.Sort(sched.queue)
} else {
d := a0.GetNextStartTime().Sub(now)
timespans.Logger.Info(fmt.Sprintf("Timer set to wait for %v", d))
timer = time.NewTimer(d)
select {
case <-timer.C:
// timer has expired
timespans.Logger.Info(fmt.Sprintf("Time for action on %v", s.queue[0]))
case <-restartLoop:
// nothing to do, just continue the loop
}
}
}
}
func loadActionTimings(storage timespans.DataStorage) {
actionTimings, err := storage.GetAllActionTimings()
if err != nil {
timespans.Logger.Warning(fmt.Sprintf("Cannot get action timings: %v", err))
}
// recreate the queue
sched.queue = timespans.ActionTimingPriotityList{}
for key, ats := range actionTimings {
toBeSaved := false
isAsap := false
newAts := make([]*timespans.ActionTiming, 0)
for _, at := range ats {
isAsap = at.CheckForASAP()
toBeSaved = toBeSaved || isAsap
if at.IsOneTimeRun() {
timespans.Logger.Info(fmt.Sprintf("Time for one time action on %v", at))
go at.Execute()
// do not append it to the newAts list to be saved
} else {
sched.queue = append(sched.queue, at)
newAts = append(newAts, at)
}
}
if toBeSaved {
storage.SetActionTimings(key, newAts)
}
}
sort.Sort(sched.queue)
}