Service.go
package core
import (
"sync"
"time"
)
type Timer struct {
start time.Time
}
func NewTimer() *Timer {
return &Timer{start: time.Now()}
}
func (t *Timer) LastInterval() time.Duration {
return time.Since(t.start)
}
func (t *Timer) Check() {
t.start = time.Now()
}
type Service struct {
args map[string]string
routine []Routine
pointer int
queue chan func()
iterate time.Duration
queueWait sync.WaitGroup
}
type Routine struct {
function func()
timer *Timer
ucycle time.Duration
}
func NewService() *Service {
return &Service{
args: make(map[string]string),
routine: []Routine{},
queue: make(chan func(), 100), // Buffered channel to handle tasks
iterate: time.Millisecond * 100,
}
}
func (s *Service) SetArgs(args map[string]string) {
s.args = args
}
func (s *Service) GetArgs() map[string]string {
return s.args
}
func (s *Service) Init() {
// Override to provide initialization logic
}
func (s *Service) Main() {
s.TaskRoutine()
s.TaskQueue()
s.Iterate()
}
func (s *Service) Iterate() {
time.Sleep(s.iterate)
}
func (s *Service) TaskRoutine() {
if len(s.routine) == 0 {
return
}
if s.pointer >= len(s.routine) {
s.pointer = 0
}
routine := s.routine[s.pointer]
s.pointer++
if time.Since(routine.timer.start) > routine.ucycle {
routine.function()
routine.timer.Check()
}
}
func (s *Service) TaskQueue() {
select {
case task := <-s.queue:
if task != nil {
task()
}
default:
}
}
func (s *Service) AddRoutine(function func(), ucycle time.Duration) {
s.routine = append(s.routine, Routine{
function: function,
timer: NewTimer(),
ucycle: ucycle,
})
}
func (s *Service) AddQueue(task func()) {
s.queueWait.Add(1)
s.queue <- func() {
defer s.queueWait.Done()
task()
}
}
func (s *Service) WaitQueue() {
s.queueWait.Wait()
}Timer ๊ตฌ์กฐ์ฒด์ ๋ฉ์๋
Service ๊ตฌ์กฐ์ฒด์ ๋ฉ์๋
์์ฝ
Last updated