1. 延时任务
JDK 原型单点延时或定时任务:自从JDK1.5之后,提供了ScheduledExecutorService
代替TimerTask来执行延时
或定时任务,提供了不错的可靠性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class ScheduledExecutorTest { public static void main(String[] args) { ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1); scheduledExecutor.schedule(() -> { System.out.println("线程执行任务:" + Thread.currentThread().getName()); }, 5, TimeUnit.SECONDS); scheduledExecutor.shutdown(); System.out.println("主线程结束: " + Thread.currentThread().getName());
} }
|
1 2 3 4 5
| public ScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit );
|
2. 异步任务
2.1 编写异步任务类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component;
@Component public class AsyncTask { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class) ;
@Async public void asyncTask0 () { try{ Thread.sleep(5000); }catch (Exception e){ e.printStackTrace(); } LOGGER.info("======异步任务结束0======"); } @Async("asyncExecutor1") public void asyncTask1 () { try{ Thread.sleep(5000); }catch (Exception e){ e.printStackTrace(); } LOGGER.info("======异步任务结束1======"); } }
|
2.2 指定异步任务执行的线程池
这里可以不指定,指定执行的线程池,可以更加方便的监控和管理异步任务的执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor;
@Configuration public class TaskPoolConfig { @Bean("asyncExecutor1") public Executor taskExecutor1 () { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(200); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("asyncTask1-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(600); return executor; } }
|
2.3 启动类添加异步注解
1 2 3 4 5 6 7
| @EnableAsync @SpringBootApplication public class TaskApplication { public static void main(String[] args) { SpringApplication.run(TaskApplication.class,args) ; } }
|
2.4 异步调用的测试接口
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RestController public class TaskController { @Resource private AsyncTask asyncTask ; @RequestMapping("/asyncTask") public String asyncTask (){ asyncTask.asyncTask0(); asyncTask.asyncTask1(); return "success" ; } }
|