导入依赖:
springBoot已经默认集成了定时任务的依赖,只需要引入基本的依赖就可以使用定时任务。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
启动配置类中加入@EnableScheduling注解,意思是开启定时任务。
@SpringBootApplication
@EnableScheduling
public class SpringbootExcelApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootExcelApplication.class, args);
}
}
只定义一个任务时
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class ScheduleTask {
@Scheduled(cron = "*/1 * * * * ?")
public void execute1(){
System.out.println(Thread.currentThread().getName()+"任务2每隔1s就执行");
}
}
执行结果如下:
当任务执行时间比定时周期要长时:
@Scheduled(cron = "*/1 * * * * ?")
public void execute1(){
System.out.println(new Date());
try {
Thread.sleep(6000);
System.out.println(Thread.currentThread().getName()+"任务1每隔1min就执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
执行结果:
多任务时
@Component
public class ScheduleTask {
@Scheduled(cron = "0 0/1 * * * ?")
public void execute1() throws InterruptedException {
System.out.println(new Date());
//任务1每次执行花6s种
Thread.sleep(6000);
System.out.println(Thread.currentThread().getName()+"任务1每隔1min就执行");
}
@Scheduled(cron = "0 0/1 * * * ?")
public void execute2(){
System.out.println(new Date());
System.out.println(Thread.currentThread().getName()+"任务2每隔1min就执行");
}
}
执行结果:可以看出任务一和任务二都是在同一线程下执行的,任务一执行完成后,在执行任务二,这与我们期望的不一样。所以多任务执行时,需要开启多线程。
Mon Jan 18 16:15:00 CST 2021
scheduling-1任务1每隔1min就执行
Mon Jan 18 16:15:06 CST 2021
scheduling-1任务2每隔1min就执行
Mon Jan 18 16:16:00 CST 2021
scheduling-1任务1每隔1min就执行
Mon Jan 18 16:16:06 CST 2021
scheduling-1任务2每隔1min就执行
开启多线程后:
定义一个配置类开启多线程:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(3));
}
}
执行结果:
Mon Jan 18 16:22:00 CST 2021
Mon Jan 18 16:22:00 CST 2021
pool-1-thread-2任务2每隔1min就执行
pool-1-thread-1任务1每隔1min就执行
Mon Jan 18 16:23:00 CST 2021
pool-1-thread-3任务2每隔1min就执行
Mon Jan 18 16:23:00 CST 2021
pool-1-thread-1任务1每隔1min就执行
cron表达式
https://www.bejson.com/othertools/cron/