spring boot实现定时任务比较简单,基于注解(@Scheduled)就够了,只需几行代码便可完成。 代码如下:
package com.china.great.amos.chinagreatblog.thread;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Author: Liu HongYang
* @DateTime: 2020/5/19 12:46 下午
* @Description: TODO
*/
@Component
@EnableScheduling
public class InsertJob {
/**默认是fixedDelay 上一次执行完毕时间后执行下一轮*/
@Scheduled(cron = "0/5 * * * * *")
public void run() throws InterruptedException {
//Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+"=====>>>>>5秒使用cron {}"+(System.currentTimeMillis()/1000));
}
}
Cron表达式参数分别表示:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。
到此定时任务的功能就完成了,此时,如果有多个任务呢,那就需要多个线程来执行了,需要配置线程池,上代码:
package com.china.great.amos.chinagreatblog.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* @Author: Liu HongYang
* @DateTime: 2020/5/20 10:36 上午
* @Description: TODO
*/
@Configuration
@EnableAsync
public class AsyncConfig {
//核心线程数
private int corePoolSize = 10;
//最大线程数
private int maxPoolSize = 200;
//队列数
private int queueCapacity = 10;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
配置完毕,接着在刚刚的InsertJob类上面加上注解@Async,大功告成
,执行的结果如下图,都是不同的线程