-
Notifications
You must be signed in to change notification settings - Fork 68
/
application.go
103 lines (85 loc) · 2.41 KB
/
application.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package schedule
import (
"time"
"github.com/robfig/cron/v3"
"github.com/goravel/framework/contracts/cache"
"github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/log"
"github.com/goravel/framework/contracts/schedule"
"github.com/goravel/framework/support/carbon"
"github.com/goravel/framework/support/color"
)
type Application struct {
artisan console.Artisan
cache cache.Cache
cron *cron.Cron
log log.Log
}
func NewApplication(artisan console.Artisan, cache cache.Cache, log log.Log) *Application {
return &Application{
artisan: artisan,
cache: cache,
log: log,
}
}
func (app *Application) Call(callback func()) schedule.Event {
return NewCallbackEvent(callback)
}
func (app *Application) Command(command string) schedule.Event {
return NewCommandEvent(command)
}
func (app *Application) Register(events []schedule.Event) {
if app.cron == nil {
app.cron = cron.New(cron.WithLogger(NewLogger(app.log)))
}
app.addEvents(events)
}
func (app *Application) Run() {
app.cron.Run()
}
func (app *Application) addEvents(events []schedule.Event) {
for _, event := range events {
chain := cron.NewChain(cron.Recover(NewLogger(app.log)))
if event.GetDelayIfStillRunning() {
chain = cron.NewChain(cron.DelayIfStillRunning(NewLogger(app.log)), cron.Recover(NewLogger(app.log)))
} else if event.GetSkipIfStillRunning() {
chain = cron.NewChain(cron.SkipIfStillRunning(NewLogger(app.log)), cron.Recover(NewLogger(app.log)))
}
_, err := app.cron.AddJob(event.GetCron(), chain.Then(app.getJob(event)))
if err != nil {
app.log.Errorf("add schedule error: %v", err)
}
}
}
func (app *Application) getJob(event schedule.Event) cron.Job {
return cron.FuncJob(func() {
if event.IsOnOneServer() && event.GetName() != "" {
if app.cache.Lock(event.GetName()+carbon.Now().Format("Hi"), 1*time.Hour).Get() {
app.runJob(event)
}
} else {
app.runJob(event)
}
})
}
func (app *Application) runJob(event schedule.Event) {
if event.GetCommand() != "" {
app.artisan.Call(event.GetCommand())
} else {
event.GetCallback()()
}
}
type Logger struct {
log log.Log
}
func NewLogger(log log.Log) *Logger {
return &Logger{
log: log,
}
}
func (log *Logger) Info(msg string, keysAndValues ...any) {
color.Green().Printf("%s %v\n", msg, keysAndValues)
}
func (log *Logger) Error(err error, msg string, keysAndValues ...any) {
log.log.Error(msg, keysAndValues)
}