crontab4j

A utility to be for using CRON expressions in Java

View project on GitHub

License

Quick start

Goal

This library allows for the triggering of a Java job based on a CRON expression.

Supported CRON syntaxes

At the moment

  • Unix
    • Classic integer ranges
    • Day and month names (3 letters, case insensitive)
    • Special expressions, with the exception of @reboot

Planned for later

  • cron4j
  • Quartz (but CRONs are only a little part of it)
  • crontab4j (take the best of each world and make it the most flexible as can be)

How to use it

import org.keyboardplaying.cron.parser.UnixCronParser;
import org.keyboardplaying.cron.scheduler.CronScheduler;

public class CronStarter {

    public static void main(String[] args) {
        CronScheduler schd = new CronScheduler();
        // Set parser: only Unix at the moment, but more to come
        schd.setParser(new UnixCronParser());
        schd.scheduleJob(new Runnable() {
            public void run() {
                System.out.println("Another minute ticked.");
            }
        }, "* * * * *");
        // schd is a daemon: it will not prevent the JVM from stopping
    }
}

Daemon

The JVM will stop automatically if all remaining threads are daemons. The CronScheduler is a daemon by default. To prevent this behaviour, you should instantiate it this way:

CronScheduler schd = new CronScheduler(false);

A fair warning: you will have to stop it for the JVM to close:

schd.terminate();

Using with Spring

<bean id="schd" class="org.keyboardplaying.cron.scheduler.CronScheduler">
    <property name="parser"><bean class="org.keyboardplaying.cron.parser.UnixCronParser"/></property>
    <property name="jobs">
        <list>
            <ref bean="job1"/>
            <ref bean="job2"/>
            ...
        </list>
    </property>
</bean>

<bean id="job1" class="org.keyboardplaying.cron.scheduler.CronJob">
    <property name="job" ref="myRunnableBean"/>
    <property name="cron" value="0 0 * * *"/>
</bean>

...

Interesting links

History

It happened at work: we wanted to gain the flexibility of CRON expressions for job scheduling, but my boss feared Quartz was overkill for a single job.

So I gathered my knowledge about the CRONs (which was few, so I had to look for some more) and created my own parser and scheduler. Not that hard, actually, but this was a kind of a draft.

I had the wish to go from scratch and write something a bit more elaborate and clean. And when looking for the name, I discovered cron4j was already taken by a similar project. Still, for the challenge...

My first try had been using joda-time for comfort and ease of use. However, this time, I chose to avoid external libraries as much as possible in order to keep the footprint as light as possible, and therefore used java.util.Calendar instead.