Master Spring Boot Scheduling: From @EnableScheduling to Quartz Integration
This guide explains how to implement periodic tasks in Spring Boot 2.2.11 using the built‑in @EnableScheduling/@Scheduled approach and the Quartz library, covering configuration, cron expressions, core Quartz concepts, and complete code examples for both methods.
Method 1: Spring Boot built‑in scheduling
Enable the scheduling feature with @EnableScheduling in the main application class and define a task class annotated with @Component and @Scheduled. The example runs a simple method every 3 seconds and prints a message.
@SpringBootApplication
@EnableScheduling
public class SpringBootQuartzSchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootQuartzSchedulerApplication.class, args);
}
}
@Component
public class JobExecutor {
// Every 3 seconds
@Scheduled(fixedDelay = 3000)
public void process() {
System.out.println("执行任务");
}
}The @Scheduled annotation supports several attributes: fixedDelay: fixed pause (ms) between the end of the last execution and the start of the next. fixedRate: fixed period (ms) between successive starts. initialDelay: initial wait before the first execution. cron: a cron expression (six‑field format for Spring Boot).
Example of using a cron expression from configuration:
@Scheduled(cron = "${custom.cron}")Configuration (application.yml):
server:
port: 8080
custom:
cron: 0/3 * * * * ?Spring Boot cron fields (seconds, minutes, hours, day‑of‑month, month, day‑of‑week) are explained, including special symbols such as *, ?, -, ,, and / with usage examples.
Method 2: Quartz scheduling
Quartz provides a richer scheduling engine. Its core concepts are:
Job : an interface with a single execute(JobExecutionContext) method where the task logic resides.
JobDetail : describes the Job class and stores static information and a JobDataMap for parameters.
Trigger : defines when a Job runs; common types are SimpleTrigger and CronTrigger.
Scheduler : the container that holds Jobs and Triggers and manages their execution.
Add the Quartz starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>Configure JobDetail, Trigger, and Scheduler beans:
@Configuration
public class QuartzConfig {
@Bean
public JobDetail sampleJobDetail() {
JobDataMap dataMap = new JobDataMap();
dataMap.put("k1", "v1");
return JobBuilder.newJob(SampleJob.class)
.withIdentity("sampleJob")
.usingJobData("key", "pack")
.usingJobData(dataMap)
.storeDurably()
.build();
}
/** Simple trigger: every 2 seconds, repeat forever */
@Bean
public Trigger sampleJobTrigger() {
SimpleScheduleBuilder scheduleBuilder =
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.repeatForever();
return TriggerBuilder.newTrigger()
.forJob(sampleJobDetail())
.withIdentity("sampleTrigger")
.withSchedule(scheduleBuilder)
.build();
}
}Define the Job implementation:
public class SampleJob extends QuartzJobBean {
private static final Logger logger = LoggerFactory.getLogger(SampleJob.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.info("这里是一个简单的任务");
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
logger.info("任务数据:key = {}, value = {}", entry.getKey(), entry.getValue());
}
}
}Optionally create a cron‑based trigger:
@Bean
public Trigger cronJobTrigger() {
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
return TriggerBuilder.newTrigger()
.forJob(sampleJobDetail())
.withIdentity("t1", "CRON")
.withSchedule(scheduleBuilder)
.build();
}After starting the Spring Boot application, Quartz will manage the defined jobs according to the configured triggers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
