-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
83 lines (72 loc) · 1.95 KB
/
task.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
package models
import (
"os/exec"
"strings"
"time"
"github.com/khoa-le/crontask/utils"
"gopkg.in/robfig/cron.v2"
"github.com/jinzhu/gorm"
"github.com/mrkaspa/go-helpers"
)
//Task executed recurrently
type Task struct {
ID string `sql:"type:varchar(100)" gorm:"primary_key" json:"id"`
Name string `json:"name" validate:"required"`
Periodicity string `json:"periodicity" validate:"required"`
CronID int `json:"-"`
Command string `json:"command" validate:"required"`
CreatedAt time.Time `json:"created_at"`
}
//BeforeCreate callback
func (t *Task) BeforeCreate() {
if t.ID == "" {
t.ID = helpers.PseudoUUID()
}
}
//AfterCreate callback
func (t *Task) AfterCreate(txn *gorm.DB) error {
return t.Start(txn)
}
//AfterUpdate callback
func (t *Task) AfterUpdate(txn *gorm.DB) error {
if err := t.Stop(txn); err != nil {
return err
}
return t.Start(txn)
}
//BeforeDelete callback
func (t *Task) BeforeDelete(txn *gorm.DB) error {
return t.Stop(txn)
}
//Start the task
func (t *Task) Start(txn *gorm.DB) error {
utils.Log.Info("Startin!!")
if t.Periodicity == "stop" {
return txn.Model(t).UpdateColumn("cron_id", 0).Error
}
pid, err := MasterCron.AddFunc(t.Periodicity, func() {
commandArr := strings.Split(t.Command, " ")
command, args := commandArr[0], commandArr[1:]
utils.Log.Infof("Running command %s with args: %v", command, args)
resp, err := exec.Command(command, args...).Output()
if err != nil {
utils.Log.Error(err)
}
utils.Log.Infof("Output: %s", string(resp))
})
if err != nil {
return err
}
utils.Log.Infof("The task %s has been started", t.ID)
return txn.Model(t).UpdateColumn("cron_id", int(pid)).Error
}
//Stop the task
func (t *Task) Stop(txn *gorm.DB) error {
if t.CronID != 0 {
entryID := cron.EntryID(t.CronID)
MasterCron.Remove(entryID)
utils.Log.Infof("The task %s has been stopped", t.ID)
return txn.Model(t).UpdateColumn("cron_id", 0).Error
}
return nil
}