Quartz in Spring Boot

🔹 What is Quartz?

Quartz is a powerful, open-source job scheduling library. It lets you schedule tasks (jobs) to run:

  • At a fixed interval
  • At a specific time
  • Using cron expressions

🔹 Add Quartz Dependency

In a Spring Boot (Maven) project, include:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

🔹 Define a Quartz Job

Quartz jobs implement the Job interface.

package com.example.demo.jobs;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SampleJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(SampleJob.class);

    @Override
    public void execute(JobExecutionContext context) {
        logger.info("✅ SampleJob is running at {}", context.getFireTime());
    }
}

🔹 Configure Quartz Scheduler

You can define job details and triggers in a @Configuration class.

package com.example.demo.config;

import com.example.demo.jobs.SampleJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {

    // Define the job
    @Bean
    public JobDetail sampleJobDetail() {
        return JobBuilder.newJob(SampleJob.class)
                .withIdentity("sampleJob")
                .storeDurably()
                .build();
    }

    // Define the trigger (run every 10 seconds)
    @Bean
    public Trigger sampleJobTrigger(JobDetail sampleJobDetail) {
        return TriggerBuilder.newTrigger()
                .forJob(sampleJobDetail)
                .withIdentity("sampleTrigger")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(10)
                        .repeatForever())
                .build();
    }
}

🔹 Application Properties (Optional)

If you want Quartz to use a database instead of in-memory, you can configure:

spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=always

(Default is in-memory job store, fine for small apps.)


🔹 Run the App

When you run the Spring Boot app, you should see logs like:

✅ SampleJob is running at 2025-08-21T10:00:00
✅ SampleJob is running at 2025-08-21T10:00:10
✅ SampleJob is running at 2025-08-21T10:00:20

🔹 Example with CRON Expression

You can swap the trigger for a cron schedule:

@Bean
public Trigger sampleJobTrigger(JobDetail sampleJobDetail) {
    return TriggerBuilder.newTrigger()
            .forJob(sampleJobDetail)
            .withIdentity("sampleCronTrigger")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/30 * * * * ?")) // every 30 seconds
            .build();
}

Leave a Reply