master
Evan Chen 2021-12-18 21:32:46 +08:00
parent 796a2f4d8c
commit e3b864e29d
5 changed files with 46 additions and 9 deletions

View File

@ -84,6 +84,9 @@ func Start(r Receiver) {
}
func Stop() {
if len(started) == 0 {
return
}
quit <- struct{}{}
log.Debug().Str("mod", "history").Msg("stop received")
wg.Wait()

View File

@ -1,12 +1,26 @@
package task
import (
"sync"
"time"
cron "github.com/robfig/cron/v3"
)
var Reporter chan *Report
var started chan struct{}
var wg sync.WaitGroup
var quit chan struct{}
func init() {
Reporter = make(chan *Report)
started = make(chan struct{}, 1)
quit = make(chan struct{}, 1)
}
type Receiver func(*Report)
var ReportReceiver Receiver = func(r *Report) {}
type Report struct {
// Entry

View File

@ -18,6 +18,6 @@ func (srv Service) Del() {
if c == nil {
return
}
<-Stop().Done()
Stop()
}
func (srv Service) Health() error { return nil }

View File

@ -1,7 +1,6 @@
package task
import (
"context"
"fmt"
"time"
@ -16,7 +15,6 @@ var c *cron.Cron
func init() {
// viper.Set("task.runner", 5)
Reporter = make(chan *Report)
}
func Init() {
@ -62,13 +60,13 @@ func (t *_task) Run() {
}
defer func() {
if err := recover(); err != nil {
log.Error().Str("error", fmt.Sprint(err)).Msg("")
l.Error().Str("error", fmt.Sprint(err)).Msg("")
} else if t.once {
c.Remove(t.id)
}
}()
if err := t.Task.Func(t.carry, t.args...); err != nil {
log.Error().Err(err).Str("taskname", t.Task.Name).Msg("")
l.Error().Err(err).Str("taskname", t.Task.Name).Msg("")
Reporter <- &Report{
Entry: t.id,
Name: t.Task.Name,
@ -85,9 +83,31 @@ func (t *_task) Run() {
}
func Start() {
if len(started) == 1 {
return
}
started <- struct{}{}
c.Start()
go func() {
for {
select {
case r := <-Reporter:
wg.Add(1)
ReportReceiver(r)
wg.Done()
case <-quit:
<-started
return
}
}
}()
}
func Stop() context.Context {
return c.Stop()
func Stop() {
if len(started) == 0 {
return
}
quit <- struct{}{}
<-c.Stop().Done()
wg.Wait()
}

View File

@ -82,7 +82,7 @@ func TestOverall(t *testing.T) {
lg.Info().Msgf("%v", GetTasks())
Start()
<-time.After(time.Second * 20)
<-Stop().Done()
Stop()
}
@ -120,5 +120,5 @@ func TestReporter(t *testing.T) {
}()
<-time.After(time.Second * 20)
<-Stop().Done()
Stop()
}