Simple Job Scheduling in Java CDI with Quartz Integration

A practical guide demonstrating how to implement job scheduling in a Java CDI environment using a custom CDI extension powered by the Quartz Framework. The solution requires minimal setup - just a Maven dependency and a @Cron annotation - making it an elegant approach to scheduling tasks in enterprise Java applications. The implementation supports different scheduling frameworks through a built-in scheduler abstraction, offering flexibility and maintainability.

1 Minutes reading time

Behold the masterpiece that AI hallucinated while reading this post:

"The Little Java Application That Learned To Tell Time"

(after I fed it way too many marketing blogs and memes)

Created using DALL-E 3

AI-Generated: The Little Java Application That Learned To Tell Time

Often we need to schedule Jobs. Standard Java CDI does not have a build in Job Scheduler feature. But this functionality can be easily implemented by using the CDI extension mechanism.

I wrote a simple CDI extension for Job scheduling backed by the Quartz Framework. It is hosted at Github.

To schedule a Job, we basically need to do the following things:

a) add the following Maven dependency(available from Central Repository):

<dependency>
    <groupId>de.mirkosertic.cdicron</groupId>
    <artifactId>cdi-cron-quartz-scheduler</artifactId>
    <version>1.0</version>
</dependency>

b) implement a Bean with the Job implementation:

import de.mirkosertic.cdicron.api.Cron;

@Singleton
public class DummyJob {

    public static final AtomicLong COUNTER = new AtomicLong(0);

    @Cron(cronExpression = "0/2 * * * * ?")
    public void scheduledMethod() {
        COUNTER.incrementAndGet();
    }
}

Nothing else to do :-) The Job scheduler is booted by the CDI extension and will schedule the annotated method as defined by the supplied cron expression.The cdicron project comes with a built in scheduler abstraction. So it is quite easy to support other scheduling frameworks without changing existing code. Take a look at the GitHub project for more information.

I really love CDI!

Git revision: 2e692ad