-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 97f8cfe
Showing
12 changed files
with
808 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
.idea | ||
.DS_Store | ||
.build/* |
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,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2020 Sergei Vizel | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
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,135 @@ | ||
# go-cron | ||
|
||
Cron is a system daemon used to execute desired tasks (in the background) at designated times. | ||
|
||
Binaries can be found at: https://github.com/cravler/go-cron/releases | ||
|
||
## Usage | ||
|
||
```sh | ||
cron --help | ||
``` | ||
|
||
`crontab.yaml` example: | ||
|
||
```yaml | ||
exp: "@every 1h15m5s" | ||
cmd: | ||
name: "ls" | ||
argv: | ||
- "-lah" | ||
- "--color=auto" | ||
dir: "/var/www" | ||
log: | ||
# Combined output (stdout & stderr) | ||
file: "/var/log/app-1.log" | ||
--- | ||
exp: "5 15 */1 * * ?" | ||
# Skip command run, if previous still running | ||
lock: true | ||
cmd: | ||
name: "env" | ||
env: | ||
- "TEST1=123" | ||
- "TEST2=456 789" | ||
log: | ||
# If file empty, we can specify (stdout & stderr) | ||
# Defaults to "". | ||
file: "" | ||
# The maximum size of the log before it is rolled. | ||
# A positive integer plus a modifier representing | ||
# the unit of measure (k, m, or g). | ||
# Defaults to 0 (unlimited). | ||
size: 1m | ||
# The maximum number of log files that can be present. | ||
# If rolling the logs creates excess files, | ||
# the oldest file is removed. | ||
# Only effective when size is also set. | ||
# A positive integer. | ||
# Defaults to 1. | ||
num: 3 | ||
stdout: | ||
file: "/var/log/app-2-stdout.log" | ||
stderr: | ||
file: "/var/log/app-2-stderr.log" | ||
size: 5m | ||
num: 1 | ||
``` | ||
### CRON Expression Format | ||
A cron expression represents a set of times, using 5-6 space-separated fields. | ||
Field name | Mandatory? | Allowed values | Allowed special characters | ||
-------------|:----------:|:-------------------:|:--------------------------: | ||
Seconds | No | `0-59` | `* / , -` | ||
Minutes | Yes | `0-59` | `* / , -` | ||
Hours | Yes | `0-23` | `* / , -` | ||
Day of month | Yes | `1-31` | `* / , - ?` | ||
Month | Yes | `1-12` or `JAN-DEC` | `* / , -` | ||
Day of week | Yes | `0-6` or `SUN-SAT` | `* / , - ?` | ||
|
||
`Month` and `Day of week` field values are case insensitive. `SUN`, `Sun`, and `sun` are equally accepted. | ||
|
||
#### Special Characters | ||
|
||
##### Asterisk `*` | ||
|
||
The asterisk indicates that the cron expression will match for all values of the field; e.g., using an asterisk in | ||
the `month` field would indicate every month. | ||
|
||
##### Slash `/` | ||
|
||
Slashes are used to describe increments of ranges. For example `3-59/15` in the `minutes` field would indicate | ||
the 3rd minute of the hour and every 15 minutes thereafter. The form `*/...` is equivalent to the form `first-last/...`, | ||
that is, an increment over the largest possible range of the field. The form `N/...` is accepted as meaning `N-MAX/...`, | ||
that is, starting at N, use the increment until the end of that specific range. It does not wrap around. | ||
|
||
##### Comma `,` | ||
|
||
Commas are used to separate items of a list. For example, using `MON,WED,FRI` in the `day of week` field would mean | ||
Mondays, Wednesdays and Fridays. | ||
|
||
##### Hyphen `-` | ||
|
||
Hyphens are used to define ranges. For example, `9-17` would indicate every hour between 9am and 5pm inclusive. | ||
|
||
##### Question mark `?` | ||
|
||
Question mark may be used instead of `*` for leaving either `day of month` or `day of week` blank. | ||
|
||
#### Predefined schedules | ||
|
||
You may use one of several pre-defined schedules in place of a cron expression. | ||
|
||
Entry | Description | Equivalent To | ||
-----------------------|--------------------------------------------|:-------------: | ||
@yearly (or @annually) | Run once a year, midnight, Jan. 1st | `0 0 1 1 *` | ||
@monthly | Run once a month, midnight, first of month | `0 0 1 * *` | ||
@weekly | Run once a week, midnight between Sat/Sun | `0 0 * * 0` | ||
@daily (or @midnight) | Run once a day, midnight | `0 0 * * *` | ||
@hourly | Run once an hour, beginning of hour | `0 * * * *` | ||
|
||
##### @every `<duration>` | ||
|
||
where `duration` is a string with time units: `s`, `m`, `h`. | ||
|
||
Entry | Description | Equivalent To | ||
---------------|--------------------------------------------|:--------------: | ||
@every 5s | Run every 5 seconds | `*/5 * * * * ?` | ||
@every 15m5s | Run every 15 minutes 5 seconds | `5 */15 * * * ?` | ||
@every 1h15m5s | Run every 1 hour 15 minutes 5 seconds | `5 15 */1 * * ?` | ||
|
||
#### Time zones | ||
|
||
By default, all scheduling is done in the machine's local time zone. | ||
Individual cron schedules may also override the time zone they are to be interpreted in by providing an additional | ||
space-separated field at the beginning of the cron spec, of the form `CRON_TZ=Europe/London`. | ||
|
||
For example: | ||
|
||
```yaml | ||
exp: "CRON_TZ=Europe/London 0 6 * * ?" # Runs at 6am in Europe/London | ||
``` | ||
|
||
Be aware that jobs scheduled during daylight-savings leap-ahead transitions will not be run! |
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,161 @@ | ||
package main | ||
|
||
import ( | ||
"io" | ||
"os" | ||
"log" | ||
"path" | ||
"strings" | ||
"syscall" | ||
"os/exec" | ||
"os/signal" | ||
|
||
"github.com/spf13/cobra" | ||
"github.com/robfig/cron/v3" | ||
|
||
"github.com/cravler/go-cron/internal/app" | ||
) | ||
|
||
var version = "0.x-dev" | ||
|
||
var logger = log.New(os.Stderr, "", log.LstdFlags) | ||
|
||
func main() { | ||
rootCmdName := path.Base(os.Args[0]) | ||
rootCmd := app.NewRootCmd(rootCmdName, version, func(c *cobra.Command, args []string) error { | ||
workdir, _ := c.Flags().GetString("workdir") | ||
verbose, _ := c.Flags().GetBool("verbose") | ||
|
||
runApp(args, workdir, verbose) | ||
|
||
return nil | ||
}) | ||
|
||
rootCmd.Flags().StringP("workdir", "w", "", "Working directory") | ||
rootCmd.Flags().BoolP("verbose", "v", false, "Verbose output") | ||
|
||
if err := rootCmd.Execute(); err != nil { | ||
rootCmd.Println(err) | ||
os.Exit(1) | ||
} | ||
} | ||
|
||
func runApp(args []string, workdir string, verbose bool) { | ||
l := cron.PrintfLogger(logger) | ||
p := cron.NewParser(cron.SecondOptional |cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor) | ||
c := cron.New(cron.WithParser(p), cron.WithLogger(l)) | ||
|
||
entries := []app.Entry{} | ||
for _, crontab := range args { | ||
if err := app.GetEntries(crontab, &entries); err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} | ||
} | ||
|
||
for _, raw := range entries { | ||
entry := raw | ||
|
||
tz, exp, err := app.Parse(entry.Exp) | ||
if err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
continue | ||
} | ||
|
||
if strings.TrimSpace(tz + " " + exp) != strings.TrimSpace(entry.Exp) { | ||
entry.Exp = entry.Exp + " (" + exp + ")" | ||
} | ||
|
||
if err := app.PrepareLogs(&entry); err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} | ||
|
||
if verbose { | ||
d, _ := app.DumpYaml("Add", entry) | ||
logger.Printf("%s\n", d) | ||
} | ||
|
||
schedule, err := p.Parse(strings.TrimSpace(tz + " " + exp)) | ||
if err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
continue | ||
} | ||
|
||
fn := func() { | ||
if verbose { | ||
d, _ := app.DumpYaml("Execute", entry) | ||
logger.Printf("%s\n", d) | ||
} | ||
|
||
cmd := exec.Command(entry.Cmd.Name, entry.Cmd.Argv...) | ||
cmd.Env = os.Environ() | ||
if entry.Cmd.Env != nil { | ||
cmd.Env = append(cmd.Env, entry.Cmd.Env...) | ||
} | ||
if entry.Cmd.Dir != "" { | ||
cmd.Dir = entry.Cmd.Dir | ||
} else if workdir != "" { | ||
cmd.Dir = workdir | ||
} | ||
|
||
var outFile, errFile io.WriteCloser | ||
|
||
if entry.Log.File != "" { | ||
file, err := app.OpenLogFile(entry.Log, "", 0) | ||
if err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} else { | ||
defer file.Close() | ||
outFile = file | ||
errFile = file | ||
} | ||
} else { | ||
if entry.Stdout.File != "" { | ||
file, err := app.OpenLogFile(entry.Stdout, entry.Log.Size, entry.Log.Num) | ||
if err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} else { | ||
defer file.Close() | ||
outFile = file | ||
} | ||
} | ||
if entry.Stderr.File != "" { | ||
file, err := app.OpenLogFile(entry.Stderr, entry.Log.Size, entry.Log.Num) | ||
if err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} else { | ||
defer file.Close() | ||
errFile = file | ||
} | ||
} | ||
} | ||
|
||
if outFile != nil { | ||
cmd.Stdout = outFile | ||
} | ||
if errFile != nil { | ||
cmd.Stderr = errFile | ||
} | ||
|
||
if err := cmd.Start(); err != nil { | ||
logger.Printf("%s\n", err.Error()) | ||
} | ||
cmd.Wait() | ||
} | ||
|
||
var job cron.Job | ||
job = cron.FuncJob(fn) | ||
if entry.Lock { | ||
job = cron.NewChain(cron.SkipIfStillRunning(l)).Then(job) | ||
} | ||
|
||
c.Schedule(schedule, job) | ||
} | ||
|
||
s := make(chan os.Signal, 1) | ||
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM) | ||
defer signal.Stop(s) | ||
|
||
c.Start() | ||
<-s | ||
<-c.Stop().Done() | ||
} |
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,10 @@ | ||
module github.com/cravler/go-cron | ||
|
||
go 1.13 | ||
|
||
require ( | ||
github.com/go-pkg-hub/logrotate v0.0.0-20200227084444-f3cd25cbd19e | ||
github.com/robfig/cron/v3 v3.0.1 // indirect | ||
github.com/spf13/cobra v0.0.6 | ||
gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71 | ||
) |
Oops, something went wrong.