-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(cmd/utils/cron): Add simple cron util
- Loading branch information
1 parent
ee6c7f8
commit e1c46d2
Showing
4 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package cron | ||
|
||
import ( | ||
"log" | ||
"os" | ||
"os/exec" | ||
"strings" | ||
|
||
robfig_cron "github.com/robfig/cron/v3" | ||
|
||
parentcmd "github.com/sikalabs/tergum/cmd/utils" | ||
"github.com/spf13/cobra" | ||
) | ||
|
||
var Cmd = &cobra.Command{ | ||
Use: "cron", | ||
Short: "cron <cron-expression> <command> [args...]", | ||
Args: cobra.MinimumNArgs(2), | ||
Run: func(c *cobra.Command, args []string) { | ||
cron(args) | ||
}, | ||
} | ||
|
||
func init() { | ||
parentcmd.Cmd.AddCommand(Cmd) | ||
} | ||
|
||
func cron(args []string) { | ||
cronExpression := args[0] | ||
command := args[1] | ||
args = args[2:] | ||
|
||
c := robfig_cron.New() | ||
_, err := c.AddFunc(cronExpression, func() { | ||
log.Printf("Executing command: %s %s", command, strings.Join(args, " ")) | ||
cmd := exec.Command(command, args...) | ||
cmd.Stdout = os.Stdout | ||
cmd.Stderr = os.Stderr | ||
err := cmd.Run() | ||
if err != nil { | ||
log.Printf("Error executing command: %v", err) | ||
} | ||
}) | ||
if err != nil { | ||
log.Fatalf("Failed to add cron job: %v", err) | ||
} | ||
|
||
log.Printf("Cron scheduler started with expression: %s, command: %s %s", cronExpression, command, strings.Join(args, " ")) | ||
c.Start() | ||
|
||
// Keep the program running | ||
select {} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters