Implemented in Spring Boot timing task, we have two options, one Spring comes with the regular task processor @Scheduled notes, the other is to use third-party frameworks Quartz. Here we are two methods for simulation.
1 the timing annotation task processor @Scheduled
First, we add @EnableScheduling annotation startup class, which @EnableScheduling annotation provides support for regular tasks.
@SpringBootApplication
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Then we create a class that implements the functions of regular tasks.
@Component
public class ScheduledTest {
//fixedRate 表示两次任务的开始时间间隔
@Scheduled(fixedRate = 10000)
public void fixedRate() {
System.out.println("fixedRate " + new Date());
}
//fixedDelay 表示本次任务结束到下次任务开始之间的时间间隔。
@Scheduled(fixedDelay = 4000)
public void fixedDelay() {
System.out.println("fixedDelay " + new Date());
}
//initialDelay 表示首次任务启动的延迟时间
@Scheduled(initialDelay = 5000,fixedDelay = 2000)
public void initialDelay() {
System.out.println("initialDelay " + new Date());
}
}
Note, @ Scheduled annotation start a timed task. And all the time units are in milliseconds. Test results are as follows:
2 Quartz use
In the project, if we want to realize the function is relatively simple, you can use @Scheduled notes, otherwise we generally choose to use Quartz to achieve timing tasks.
First, use @Scheduled annotated similar add @EnableScheduling annotation startup class.
@SpringBootApplication
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Add dependence of Quartz
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
Let's create a task class needs to inherit QuartzJobBean
@Component
public class Job extends QuartzJobBean {
//执行定时任务
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("I want to do something!" + new Date());
}
}
Then we create a configuration class
@Configuration
public class QuartzConfig {
// 配置定时任务
@Bean
public JobDetail testQuartzDetail() {
return JobBuilder.newJob(Job.class).withIdentity("Job")
.storeDurably().build();
}
// 配置定时任务的触发器,也就是什么时候触发执行定时任务
@Bean(name = "jobTrigger")
public Trigger testQuartzTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(3) // 设置时间周期单位(秒)
.repeatForever();
return TriggerBuilder.newTrigger().forJob(testQuartzDetail())
.withIdentity("Job")
.withSchedule(scheduleBuilder)
.build();
}
}
The program runs as follows: