How to run Cron jobs in Java?

Better Stack Team
Updated on May 26, 2023

To run Cron jobs in Java, you can use the Quartz Scheduler library. Here are the steps to create and schedule a Java program using Quartz Scheduler:

Add Quartz dependency

You need to add the Quartz dependency in your Java project. You can add the following dependency to your Maven pom.xml file:

 
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.2</version>
</dependency>

Create a Job

Create a Java class that implements the Job interface. For example, let's say you want to print "Hello world!" every minute. You can create a Job called HelloJob with the following code:

 
public class HelloJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("Hello world!");
    }
}

Create a Trigger

Create a Trigger that specifies when the Job should run. For example, to run the HelloJob every minute, you can create a Trigger with the following code:

 
Trigger trigger = TriggerBuilder.newTrigger()
        .withIdentity("trigger1", "group1")
        .withSchedule(CronScheduleBuilder.cronSchedule("0 * * ? * *"))
        .build();

This code creates a Trigger that runs the HelloJob every minute using a Cron expression.

Create a Scheduler

Create a Scheduler that schedules the Job and Trigger. For example, you can create a Scheduler with the following code:

 
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

JobDetail job = JobBuilder.newJob(HelloJob.class)
        .withIdentity("job1", "group1")
        .build();

scheduler.scheduleJob(job, trigger);

scheduler.start();

This code creates a Scheduler that schedules the HelloJob with the specified Trigger.

Verify the Job

You can verify that the Job is running by checking the output of the Java program. You should see "Hello world!" printed to the console every minute.

By following these steps, you can create and schedule a Java program to run as a Cron job using the Quartz Scheduler library.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack