Every
Calculate even intervals for Process.send_after/3.
Sometimes we need to have periodic tasks to execute exactly at
certain intervals, for example run task every 15 minutes within hour
so we want to execute our task
- At the beginning of hour,
- 15th minute,
- 30th minute,
- 45th minute.
- etc.
So instead of doing it manually, it is better if it is automated.
Usage
Available methods
Every.minute/1
Every.minutes/2
Every.hour/1
Every.hours/2Every.minute/1 anf Every.hour/1 accepts optional parameter relative_to if provided
then makes all calculation relative to given DateTime struct.
Every.minutes/2 anf Every.hour/2 both accept time interval as a first argument and
optional parameter relative_to if provided then makes all calculation relative to
given DateTime struct. First argument is literally to be read as Every N minutes/hours.
Every.day/1 accepts optional parameter relative_to if provided
then makes all calculation relative to given DateTime struct.
All methods return duration in seconds so it is your task to turn secons into milliseconds etc.
How to use with periodic tasks
# Lets say we want to trigger our task every 5 minutes and current time is 12:02
# so next call will be at 12:05, 12:10 ... 12:55 ...
Process.send_after(self(), :work, Every.minutes(5, nil) * 1000)
# If we want to trigger every minute
Process.send_after(self(), :work, Every.minute() * 1000)
# If we want to trigger every hour
Process.send_after(self(), :work, Every.hour() * 1000)
# If we want to trigger every 2 hours
Process.send_after(self(), :work, Every.hours(2, nil) * 1000)
# If we want to trigger every day
Process.send_after(self(), :work, Every.day() * 1000)
As you can see we multiply by 1000 because return value has only second resolution.
Installation
If available in Hex, the package can be installed
by adding every to your list of dependencies in mix.exs:
def deps do
[
{:every, "~> 0.0.3"}
]
endDocumentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/every.