Elixir library for parsing, writing, and calculating Cron format strings.
Add :crontab
to your list of dependencies in mix.exs
:
def deps do
[
{:crontab, "~> 1.1"}
]
end
Everywhere you want to use the Cron expression sigil (e[cron expression]
).
import Crontab.CronExpression
An extended Cron expression has more precision than a normal Cron expression. It also specifies the second.
If you want to use extended Cron expressions with the sigil, just append an e
.
iex> import Crontab.CronExpression
iex> Crontab.DateChecker.matches_date?(~e[*/2], ~N[2017-01-01 01:01:00])
false
iex> Crontab.DateChecker.matches_date?(~e[*], ~N[2017-01-01 01:01:00])
true
All the date parameters default to now.
For previous, just replace next
in the code below.
iex> import Crontab.CronExpression
iex> Crontab.Scheduler.get_next_run_date(~e[*/2], ~N[2017-01-01 01:01:00])
{:ok, ~N[2017-01-01 01:02:00]}
iex> Crontab.Scheduler.get_next_run_date!(~e[*/2], ~N[2017-01-01 01:01:00])
~N[2017-01-01 01:02:00]
iex> Enum.take(Crontab.Scheduler.get_next_run_dates(~e[*/2], ~N[2017-01-01 01:01:00]), 3)
[~N[2017-01-01 01:02:00], ~N[2017-01-01 01:04:00], ~N[2017-01-01 01:06:00]]
If you statically define cron expressions, use the ~e[cron expression]
sigil.
For dynamic cron expressions, there is a Parser module.
The parser module takes an optional extended
flag. This is to mark if the
expression contains seconds. This defaults to false
.
iex> Crontab.CronExpression.Parser.parse "* * * * *"
{:ok,
%Crontab.CronExpression{day: [:*], hour: [:*], minute: [:*],
month: [:*], weekday: [:*], year: [:*]}}
iex> Crontab.CronExpression.Parser.parse! "* * * * *"
%Crontab.CronExpression{day: [:*], hour: [:*], minute: [:*],
month: [:*], weekday: [:*], year: [:*]}
iex> Crontab.CronExpression.Composer.compose %Crontab.CronExpression{}
"* * * * * *"
iex> Crontab.CronExpression.Composer.compose %Crontab.CronExpression{minute: [9, {:-, 4, 6}, {:/, :*, 9}]}
"9,4-6,*/9 * * * * *"
Copyright (c) 2016, SK & T AG, JOSHMARTIN GmbH, Jonatan Männchen
This library is MIT licensed. See the LICENSE for details.