Giter Club home page Giter Club logo

cron-utils's Introduction

cron-utils

A Java library to parse, validate, migrate crons as well as get human readable descriptions for them. The project follows the Semantic Versioning Convention and uses Apache 2.0 license.

Gitter Chat Build Status Coverage Status

Project stats by OpenHub

Download

cron-utils is available on Maven central repository.

<dependency>
    <groupId>com.cronutils</groupId>
    <artifactId>cron-utils</artifactId>
    <version>3.1.6</version>
</dependency>

Features

  • Create arbitrary cron expressions: you can define your own cron format! Supported fields are: second, minute, hour, day of month, month, day of week, year.
  • You can flag last field as optional!
  • Supports all cron special characters: * / , -
    • Non-standard characters L, W, LW, '?' and # are supported as well!
  • Print to locale specific human readable format (English, German, Korean and Spanish are fully supported. Dutch, French, Italian and Portuguese have basic support).
  • Parse and Description process are decoupled: parse once and operate with the result!
  • Validate if cron string expressions match a cron definition using CronValidator
  • Convert crons between different cron definitions: if you need to migrate expressions, CronMapper may help you!
  • Pre-defined definitions for the following cron libraries are provided:
  • Obtain last/next execution time as well as time from last execution/time to next execution.
  • Need to map constants between different cron/time libraries? Use ConstantsMapper.

Usage Examples

Build cron definitions

//define your own cron: arbitrary fields are allowed and last field can be optional
CronDefinition cronDefinition =
    CronDefinitionBuilder.define()
        .withSeconds().and()
        .withMinutes().and()
        .withHours().and()
        .withDayOfMonth()
            .supportsHash().supportsL().supportsW().and()
        .withMonth().and()
        .withDayOfWeek()
            .withIntMapping(7, 0) //we support non-standard non-zero-based numbers!
            .supportsHash().supportsL().supportsW().and()
        .withYear().and()
        .lastFieldOptional()
        .instance();

//or get a predefined instance
cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);

Parse

//create a parser based on provided definition
CronParser parser = new CronParser(cronDefinition);
Cron quartzCron = parser.parse("0 23 ? * * 1-5 *");

Describe

//create a descriptor for a specific Locale
CronDescriptor descriptor = CronDescriptor.instance(Locale.UK);

//parse some expression and ask descriptor for description
String description = descriptor.describe(parser.parse("*/45 * * * * *"));
//description will be: "every 45 seconds"

description = descriptor.describe(quartzCron);
//description will be: "every hour at minute 23 every day between Monday and Friday"
//which is the same description we get for the cron below:
descriptor.describe(parser.parse("0 23 ? * * MON-FRI *"));

Migrate

//Migration between cron libraries is easy!
//Turn cron expressions into another format by using CronMapper:
CronMapper cronMapper =
        new CronMapper(
                cronDefinition,
                CronDefinitionBuilder.instanceDefinitionFor(CRON4J)
        );
Cron cron4jCron = cronMapper.map(quartzCron);
//and to get a String representation of it, we can use
cron4jCron.asString();//will return: 23 * * * 1-5

Validate

//Validate if a string expression matches a cron definition:
CronValidator quartzValidator = new CronValidator(cronDefinition);

//getting a boolean result:
quartzValidator.isValid("0 23 ? * * MON-FRI *");

//or returning same string if valid and raising an exception if invalid
quartzValidator.validate("0 23 ? * * MON-FRI *");

Calculate time from/to execution

//Get date for last execution
DateTime now = DateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime lastExecution = executionTime.lastExecution(now));

//Get date for next execution
DateTime nextExecution = executionTime.nextExecution(now));

//Time from last execution
Duration timeFromLastExecution = executionTime.timeFromLastExecution(now);

//Time to next execution
Duration timeToNextExecution = executionTime.timeToNextExecution(now);

Map constants between libraries

//Map day of week value from Quartz to JodaTime
int jodatimeDayOfWeek =
        ConstantsMapper.weekDayMapping(
                ConstantsMapper.QUARTZ_WEEK_DAY,
                ConstantsMapper.JODATIME_WEEK_DAY
        );

Date and time formatting for humans!

Use htime - Human readable datetime formatting for Java! Despite this functionality is not bundled in the same jar, is a cron-utils project you may find useful.

//You no longer need to remember "YYYY-MM-dd KK a" patterns.
DateTimeFormatter formatter = 
    HDateTimeFormatBuilder
	    .getInstance()
	    .forJodaTime()
	    .getFormatter(Locale.US)
	    .forPattern("June 9, 2011");
String formattedDateTime = formatter.print(lastExecution);
//formattedDateTime will be lastExecution in "dayOfWeek, Month day, Year" format

Contribute & Support!

Contributions are welcome! You can contribute by

  • starring and/or Flattring this repo!
  • requesting or adding new features. Check our roadmap!
  • enhancing existing code: ex.: provide more accurate description cases
  • testing
  • enhancing documentation
  • providing translations to support new locales
  • bringing suggestions and reporting bugs
  • spreading the word / telling us how you use it!

Check our page! For stats about the project, you can visit our OpenHUB profile.

Support us donating once or by subscription through Flattr!

Flattr this!

Other cron-utils projects

You are welcome to visit and use the following cron-utils projects:

  • htime: A Java library to make it easy for humans format a date. You no longer need to remember date time formatting chars: just write an example, and you will get the appropiate formatter.
  • cron-utils-spring: A Java library to describe cron expressions in human readable language at Spring framework, using cron-utils.

cron-utils's People

Contributors

jmrozanec avatar danilo-valente avatar emmanueltouzery avatar francisdb avatar michaelknigge avatar vtico avatar ucpwang avatar

Watchers

 avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.