This repository has been archived by the owner on Mar 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
cron_command.go
77 lines (66 loc) · 1.73 KB
/
cron_command.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
package cron
import (
"fmt"
"strconv"
"strings"
"time"
)
type ActionType string
const (
AddAction ActionType = "add"
RandomAddAction ActionType = "random"
DelAction ActionType = "del"
DeleteAction ActionType = "delete"
StopAction ActionType = "stop"
ListAction ActionType = "list"
RefreshAction ActionType = "refresh"
HelpAction ActionType = "help"
)
type CronCommand struct {
Trigger string // cron
Action ActionType
CronSpec string
Args []string
CronID string
}
func (c CronCommand) Message() string {
return strings.Join(c.Args, " ")
}
func generateCronID() string {
return strconv.FormatUint(uint64(time.Now().Unix()), 36)
}
// Scan cron add */1 * * * * * hogehoge -> cronCommand
func (c *CronCommand) Scan(command string) error {
commands := strings.Fields(command)
fmt.Println(len(commands), commands)
c.Trigger = commands[0] // cron
c.Action = ActionType(commands[1])
switch c.Action {
case AddAction, RandomAddAction:
// cron add 1 * * * * * hogehoge
if len(commands) < 9 {
return fmt.Errorf("commands length error %d", len(commands))
}
c.CronSpec = strings.Join(commands[2:8], " ")
c.Args = commands[8:]
c.CronID = generateCronID()
case DelAction, DeleteAction, StopAction:
// cron del <cron_id>
if len(commands) != 3 {
return fmt.Errorf("commands length error %d", len(commands))
}
c.CronID = commands[2]
case ListAction, RefreshAction, HelpAction:
// cron list
if len(commands) != 2 {
return fmt.Errorf("commands length error %d", len(commands))
}
}
return nil
}
func (c CronCommand) String() string {
return fmt.Sprintf("%s %s %s %s", c.Trigger, c.Action, c.CronSpec, c.Message())
}
func (c CronCommand) CronKey() string {
return c.CronID
}