@aquarela/time-to-cron
v2.0.1
Published
Convert time to cron expression
Downloads
191
Readme
@aquarela/time-to-cron
@aquarela/time-to-cron
is a utility library designed to convert time intervals into cron expressions. This package is particularly useful for developers looking to schedule tasks in environments that require cron syntax, providing a simple interface to generate accurate cron schedules.
Table of Contents
Installation
Install the package using npm:
npm install @aquarela/time-to-cron
Usage
Use the timeToCron
function to convert time values into cron expressions. Below are some examples of how to utilize this function effectively.
Importing the Function
First, import the timeToCron
function:
import { timeToCron } from "@aquarela/time-to-cron";
Examples
Convert Seconds
Convert a number of seconds to a cron expression. The value can be less than 60 or a multiple of 60.
const cronExpression = timeToCron(30);
console.log(cronExpression); // "*/30 * * * * *"
Convert Minutes
Convert a number of minutes to a cron expression. The value can be less than 60 or a multiple of 60.
const cronExpression = timeToCron(15, "minutes");
console.log(cronExpression); // "0 */15 * * * *"
Convert Hours
Convert a number of hours to a cron expression. The value must be less than 24 or a multiple of 24.
const cronExpression = timeToCron(4, "hours");
console.log(cronExpression); // "0 0 */4 * * *"
Convert Days
Convert a number of days to a cron expression. The value is the number of days between executions.
const cronExpression = timeToCron(2, "days");
console.log(cronExpression); // "0 0 0 */2 * *"
API
timeToCron(value: number, unit: TimeUnit = "seconds"): string
Converts a time value to a cron expression.
- value: The time value to convert. Must be a positive integer.
- unit: The unit of the time value. Can be
"seconds"
,"minutes"
,"hours"
, or"days"
. Default is"seconds"
.
Returns the corresponding cron expression as a string.
Throws an error if the value is not a positive integer, does not meet the unit constraints (such as being a multiple of 60 for minutes), or if an invalid time unit is provided.
Validation Rules
- Seconds: Must be less than 60 or a multiple of 60.
- Minutes: Must be less than 60 or a multiple of 60.
- Hours: Must be less than 24 or a multiple of 24.
- Days: Any positive integer value is valid.
Testing
To run the tests, execute the following command:
npm test
Repository
For more information and to contribute, visit the GitHub repository.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Author
Diego Peixoto - @diegopeixoto on GitHub