springboot使用定時任務、非同步
阿新 • • 發佈:2019-01-10
1、定時任務:純註解方式
@Configuration @EnableScheduling @Component public class TaskConfig { // 定時任務:每天凌晨3點跑定時 @Scheduled(cron = "0 0 3 * * ?") public void myTask() { System.out.println("定時任務啟動。。。。。。"); } }
2、非同步
1)註解方式開啟非同步並設定非同步執行緒池引數
@Configuration @EnableAsync public class AsyncConfig {/* 此處成員變數應該使用@Value從配置中讀取 */ /** Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize = 10; /** Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize = 200; /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private intqueueCapacity = 10; @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.initialize(); return executor; } }
2)測試非同步
@RequestMapping(value = "/api/async") @RestController public class AsyncController { @Autowired private AsyncTask asyncTask; @GetMapping(value = "/test") public String testAsync() { /* 123-->非同步,132-->同步 */ System.out.println("1"); asyncTask.async(); System.out.println("2"); return "test"; } }
@Component public class AsyncTask { @Async public void async() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("3"); } }