크론구조 개선

This commit is contained in:
Lectom C Han
2025-12-10 09:55:35 +09:00
parent 8762db2c0e
commit b1a9204e22
11 changed files with 426 additions and 102 deletions

View File

@@ -12,9 +12,10 @@ import (
)
type Config struct {
CronExpr string
ScriptPath string
Logger *log.Logger
CronExpr string
Command string
Args []string
Logger *log.Logger
}
type Scheduler struct {
@@ -29,18 +30,14 @@ func Start(cfg Config) (*Scheduler, error) {
if cfg.CronExpr == "" {
return nil, errors.New("CronExpr is required")
}
if cfg.ScriptPath == "" {
return nil, errors.New("ScriptPath is required")
if cfg.Command == "" {
return nil, errors.New("Command is required")
}
if cfg.Logger == nil {
cfg.Logger = log.Default()
}
if _, err := os.Stat(cfg.ScriptPath); err != nil {
return nil, err
}
kst, err := time.LoadLocation("Asia/Seoul")
if err != nil {
kst = time.FixedZone("KST", 9*60*60)
@@ -54,12 +51,12 @@ func Start(cfg Config) (*Scheduler, error) {
c := cron.New(cron.WithLocation(kst), cron.WithParser(parser))
c.Schedule(spec, cron.FuncJob(func() {
runScript(cfg.Logger, cfg.ScriptPath)
runCommand(cfg.Logger, cfg.Command, cfg.Args...)
}))
c.Start()
cfg.Logger.Printf("scheduler started with cron=%s script=%s tz=%s", cfg.CronExpr, cfg.ScriptPath, kst)
cfg.Logger.Printf("scheduler started with cron=%s command=%s args=%v tz=%s", cfg.CronExpr, cfg.Command, cfg.Args, kst)
return &Scheduler{
cron: c,
@@ -75,11 +72,11 @@ func (s *Scheduler) Stop() context.Context {
return s.cron.Stop()
}
func runScript(logger *log.Logger, script string) {
func runCommand(logger *log.Logger, command string, args ...string) {
start := time.Now()
logger.Printf("scheduler: running %s", script)
logger.Printf("scheduler: running %s %v", command, args)
cmd := exec.Command("/bin/bash", script)
cmd := exec.Command(command, args...)
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
duration := time.Since(start)
@@ -88,8 +85,8 @@ func runScript(logger *log.Logger, script string) {
logger.Printf("scheduler: output:\n%s", string(out))
}
if err != nil {
logger.Printf("scheduler: %s failed after %s: %v", script, duration, err)
logger.Printf("scheduler: %s failed after %s: %v", command, duration, err)
return
}
logger.Printf("scheduler: %s completed in %s", script, duration)
logger.Printf("scheduler: %s completed in %s", command, duration)
}