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,大功告成
,執行的結果如下圖,都是不同的線程