فهرست منبع

feature: Cron support (#102)

James Read 3 سال پیش
والد
کامیت
2d173266df
3فایلهای تغییر یافته به همراه53 افزوده شده و 0 حذف شده
  1. 2 0
      cmd/OliveTin/main.go
  2. 1 0
      internal/config/config.go
  3. 50 0
      internal/oncron/cron.go

+ 2 - 0
cmd/OliveTin/main.go

@@ -7,6 +7,7 @@ import (
 
 	"github.com/OliveTin/OliveTin/internal/executor"
 	grpcapi "github.com/OliveTin/OliveTin/internal/grpcapi"
+	"github.com/OliveTin/OliveTin/internal/oncron"
 	"github.com/OliveTin/OliveTin/internal/onstartup"
 	updatecheck "github.com/OliveTin/OliveTin/internal/updatecheck"
 
@@ -105,6 +106,7 @@ func main() {
 	executor := executor.DefaultExecutor()
 
 	go onstartup.Execute(cfg, executor)
+	go oncron.Schedule(cfg, executor)
 
 	go updatecheck.StartUpdateChecker(version, commit, cfg, configDir)
 

+ 1 - 0
internal/config/config.go

@@ -11,6 +11,7 @@ type Action struct {
 	Timeout       int
 	Acls          []string
 	ExecOnStartup bool
+	ExecOnCron    []string
 	Arguments     []ActionArgument
 }
 

+ 50 - 0
internal/oncron/cron.go

@@ -0,0 +1,50 @@
+package oncron
+
+import (
+	"github.com/OliveTin/OliveTin/internal/acl"
+	"github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/executor"
+	"github.com/robfig/cron/v3"
+	log "github.com/sirupsen/logrus"
+)
+
+func Schedule(cfg *config.Config, ex *executor.Executor) {
+	scheduler := cron.New(cron.WithSeconds())
+
+	for _, action := range cfg.Actions {
+		for _, cronline := range action.ExecOnCron {
+			scheduleAction(cfg, scheduler, cronline, ex, action)
+		}
+	}
+
+	scheduler.Start()
+}
+
+func scheduleAction(cfg *config.Config, scheduler *cron.Cron, cronline string, ex *executor.Executor, action config.Action) {
+	log.WithFields(log.Fields{
+		"action":   action.Title,
+		"cronline": cronline,
+	}).Infof("Scheduling Action for cron")
+
+	_, err := scheduler.AddFunc(cronline, func() {
+		req := &executor.ExecutionRequest{
+			ActionName: action.Title,
+			Cfg:        cfg,
+			Tags:       []string{"cron"},
+			AuthenticatedUser: &acl.AuthenticatedUser{
+				Username: "cron",
+			},
+		}
+
+		ex.ExecRequest(req)
+	})
+
+	if err != nil {
+		log.WithFields(log.Fields{
+			"action":    action.Title,
+			"cronError": err,
+		}).Errorf("CRON schedule error")
+		return
+	}
+
+}