cronrange

package module
Version: v0.0.0-...-b1b61d6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2022 License: MIT Imports: 7 Imported by: 0

README

cronrange

GoDoc License GitHub Action Workflow Go Report Card Codacy Badge Codecov

cronrange is a Go package for time range expression in Cron style.

In a nutshell, CronRange expression is a combination of Cron expression and time duration to represent periodic time ranges, i.e. Cron for TimeRange. And it made easier to tell if the moment falls within the any time ranges (use IsWithin() method), and what's the next occurrence (use NextOccurrences() method).

For example, every New Year's Day in Tokyo can be written as:

DR=1440; TZ=Asia/Tokyo; 0 0 1 1 *

It consists of three parts separated by a semicolon:

  • DR=1440 stands for duration in minutes, 60 * 24 = 1440 min;
  • TZ=Asia/Tokyo is optional and for time zone using name in IANA Time Zone database;
  • 0 0 1 1 * is a cron expression representing the beginning of the time range.

Installation

To download the package:

go get -u github.com/1set/cronrange

Usage

To import it in your program as:

import "github.com/1set/cronrange"

Examples can be found in GoDoc.

License

FOSSA Status

Documentation

Overview

Package cronrange parses Cron-style time range expressions.

In a nutshell, CronRange expression is a combination of Cron expression and time duration to represent periodic time ranges. And it made easier to figure out if the moment falls within the any time ranges with the IsWithin() method, and what's the next occurrence with the NextOccurrences() method.

For example, every New Year's Day in Tokyo can be written as:

DR=1440; TZ=Asia/Tokyo; 0 0 1 1 *

It consists of three parts separated by a semicolon:

  • `DR=1440` stands for duration in minutes, 60 \* 24 = 1440 min;
  • `TZ=Asia/Tokyo` is optional and for time zone using name in IANA Time Zone database (https://www.iana.org/time-zones);
  • `0 0 1 1 *` is a cron expression representing the beginning moment of the time range.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CronRange

type CronRange struct {
	// contains filtered or unexported fields
}

CronRange consists of cron expression along with time zone and duration info.

func New

func New(cronExpr, timeZone string, durationMin uint64) (cr *CronRange, err error)

New returns a CronRange instance with given config, time zone can be empty for local time zone.

It returns an error if duration is not positive number, or cron expression is invalid, or time zone doesn't exist.

Example

This example creates an instance representing every New Year's Day in Tokyo.

package main

import (
	"fmt"

	"github.com/1set/cronrange"
)

func main() {
	cr, err := cronrange.New("0 0 1 1 *", "Asia/Tokyo", 60*24)
	if err != nil {
		fmt.Println("fail to create:", err)
		return
	}

	fmt.Println(cr)
}
Output:

DR=1440; TZ=Asia/Tokyo; 0 0 1 1 *

func ParseString

func ParseString(s string) (cr *CronRange, err error)

ParseString attempts to deserialize the given expression or return failure if any parsing errors occur.

Example

This example creates an instance with an expression representing every New Year's Day in Tokyo.

package main

import (
	"fmt"

	"github.com/1set/cronrange"
)

func main() {
	cr, err := cronrange.ParseString("DR=1440;TZ=Asia/Tokyo;0 0 1 1 *")
	if err != nil {
		fmt.Println("fail to create:", err)
		return
	}

	fmt.Println(cr)
}
Output:

DR=1440; TZ=Asia/Tokyo; 0 0 1 1 *

func (*CronRange) CronExpression

func (cr *CronRange) CronExpression() string

CronExpression returns the Cron expression of the CronRange.

func (*CronRange) Duration

func (cr *CronRange) Duration() time.Duration

Duration returns the duration of the CronRange.

func (*CronRange) IsWithin

func (cr *CronRange) IsWithin(t time.Time) (within bool)

IsWithin checks if the given time falls within any time range represented by the expression.

It panics if the CronRange instance is nil or incomplete.

Example

This example shows greeting according to your local box time.

package main

import (
	"fmt"
	"time"

	"github.com/1set/cronrange"
)

func main() {
	crGreetings := make(map[*cronrange.CronRange]string)
	crExprGreetings := map[string]string{
		"DR=360; 0 6 * * *":  "Good morning!",
		"DR=360; 0 12 * * *": "Good afternoon!",
		"DR=240; 0 18 * * *": "Good evening!",
		"DR=180; 0 22 * * *": "Good night!",
		"DR=300; 0 1 * * *":  "ZzzZZzzzZZZz...",
	}

	// create cronrange from expressions
	for crExpr, greeting := range crExprGreetings {
		if cr, err := cronrange.ParseString(crExpr); err == nil {
			crGreetings[cr] = greeting
		} else {
			fmt.Println("got parse err:", err)
			return
		}
	}

	// check if current time fails in any time range
	current := time.Now()
	for cr, greeting := range crGreetings {
		if cr.IsWithin(current) {
			fmt.Println(greeting)
		}
	}
}
Output:

func (CronRange) MarshalJSON

func (cr CronRange) MarshalJSON() ([]byte, error)

MarshalJSON implements the encoding/json.Marshaler interface for serialization of CronRange.

Example

This example demonstrates serializing a struct containing CronRange to JSON.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/1set/cronrange"
)

func main() {
	cr, err := cronrange.ParseString("DR=240;TZ=America/New_York;0 8 1 1 *")
	if err != nil {
		fmt.Println("got parse err:", err)
		return
	}
	ss := struct {
		Expr *cronrange.CronRange
		Num  int
		Goal string
	}{cr, 42, "Morning"}

	if bytes, err := json.Marshal(ss); err == nil {
		fmt.Println(string(bytes))
	} else {
		fmt.Println("got marshal err:", err)
	}

}
Output:

{"Expr":"DR=240; TZ=America/New_York; 0 8 1 1 *","Num":42,"Goal":"Morning"}

func (*CronRange) NextOccurrences

func (cr *CronRange) NextOccurrences(t time.Time, count int) (occurs []TimeRange)

NextOccurrences returns the next occurrence time ranges, later than the given time.

It panics if count is less than one, or the CronRange instance is nil or incomplete.

Example

This example lists next 5 daily happy hours of Lava Lava Beach Club after 2019.11.09.

package main

import (
	"fmt"
	"time"

	"github.com/1set/cronrange"
)

func main() {
	cr, err := cronrange.New("0 15 * * *", "Pacific/Honolulu", 120)
	if err != nil {
		fmt.Println("fail to create:", err)
		return
	}

	loc, _ := time.LoadLocation("Pacific/Honolulu")
	currTime := time.Date(2019, 11, 9, 16, 55, 0, 0, loc)
	for _, happyHour := range cr.NextOccurrences(currTime, 5) {
		fmt.Println(happyHour)
	}

}
Output:

[2019-11-10T15:00:00-10:00,2019-11-10T17:00:00-10:00]
[2019-11-11T15:00:00-10:00,2019-11-11T17:00:00-10:00]
[2019-11-12T15:00:00-10:00,2019-11-12T17:00:00-10:00]
[2019-11-13T15:00:00-10:00,2019-11-13T17:00:00-10:00]
[2019-11-14T15:00:00-10:00,2019-11-14T17:00:00-10:00]

func (CronRange) String

func (cr CronRange) String() string

String returns a normalized CronRange expression, which can be consumed by ParseString().

func (*CronRange) TimeZone

func (cr *CronRange) TimeZone() string

TimeZone returns the time zone string of the CronRange.

func (*CronRange) UnmarshalJSON

func (cr *CronRange) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON implements the encoding/json.Unmarshaler interface for deserialization of CronRange.

Example

This example demonstrates deserializing JSON to a struct containing CronRange.

package main

import (
	"encoding/json"
	"fmt"

	"github.com/1set/cronrange"
)

func main() {
	js := `{"Expr":"DR=240; TZ=America/New_York; 0 8 1 1 *","Num":43,"Goal":"Morning"}`
	ss := struct {
		Expr *cronrange.CronRange
		Num  int
		Goal string
	}{}

	if err := json.Unmarshal([]byte(js), &ss); err == nil {
		fmt.Println(ss)
	} else {
		fmt.Println("got unmarshal err:", err)
	}

}
Output:

{DR=240; TZ=America/New_York; 0 8 1 1 * 43 Morning}

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange represents a time range between starting time and ending time.

func (TimeRange) String

func (tr TimeRange) String() string

String returns a string representing time range with formatted time values in Internet RFC 3339 format.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL