這篇文章主要介紹了Spring Boot多個定時器沖突怎么解決的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Spring Boot多個定時器沖突怎么解決文章都會有所收獲,下面我們一起來看看吧。
我們的訂單服務,一般會有一個待支付訂單,而這個待支付訂單是有時間限制的,比如阿里巴巴的訂單是五天,淘寶訂單是一天,拼多多訂單是一天,美團訂單是15分鐘…
基金系統中,如何同時更新多個存儲分區中的基金信息…
總的來說,實際開發中定時器需要解決多個定時器同時并發的問題,也要解決定時器之間的沖突問題
問題不大,說到并發那就離不開多線程了…慢慢看看就懂了


我們清晰的看到執行結果都是scheduling-1
就此可以判定,Springboot定時器默認的是單線程的
但是問題就來了,如果在線程爭奪資源后,某個線程需要比較長時間才能執行完,那其他的定時器怎么辦,都只能進入等待狀態,時間越久,累計等待的定時器越多,這就容易引起雪崩…
其實只需要添加一個配置類然后加注解就可以解決問題了

具體代碼如下 :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulerTaskController {
private Logger logger= LoggerFactory.getLogger(SchedulerTaskController.class);
private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
@Async("threadPoolTaskExecutor")
public void process(){
logger.info("英文:this is scheduler task runing "+(count++));
}
@Scheduled(fixedRate = 6000)
@Async("threadPoolTaskExecutor")
public void currentTime(){
logger.info("中文:現在時間"+dateFormat.format(new Date()));
}
}
具體代碼如下 :
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.ThreadPoolExecutor;
/**使用多線程的時候,往往需要創建Thread類,或者實現Runnable接口,如果要使用到線程池,我們還需要來創建Executors,
* 在使用spring中,已經給我們做了很好的支持。只要要@EnableAsync就可以使用多線程
* 通過spring給我們提供的ThreadPoolTaskExecutor就可以使用線程池。*/
//@Configuration 表示該類是一個配置類
@Configuration
@EnableAsync
//所有的定時任務都放在一個線程池中,定時任務啟動時使用不同都線程。
public class TaskScheduleConfig {
private static final int corePoolSize = 10; // 默認線程數
private static final int maxPoolSize = 100; // 最大線程數
private static final int keepAliveTime = 10; // 允許線程空閑時間(單位:默認為秒),十秒后就把線程關閉
private static final int queueCapacity = 200; // 緩沖隊列數
private static final String threadNamePrefix = "it-is-threaddemo-"; // 線程池名前綴
@Bean("threadPoolTaskExecutor") // bean的名稱,默認為首字母小寫的方法名
public ThreadPoolTaskExecutor getDemoThread(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(keepAliveTime);
executor.setKeepAliveSeconds(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
//線程池拒絕任務的處理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//初始化
executor.initialize();
return executor;
}
}然后我們可以很清晰地看到:

關于“Spring Boot多個定時器沖突怎么解決”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Spring Boot多個定時器沖突怎么解決”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。