定时任务

定时任务线程池

  1. @Configuration
  2. //开启异步事件的支持
  3. @EnableAsync
  4. public class ScheduledConfig implements SchedulingConfigurer {
  5. @Override
  6. public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  7. taskRegistrar.setScheduler(taskExecutor());
  8. }
  9. @Bean
  10. public Executor taskExecutor() {
  11. return Executors.newScheduledThreadPool(10); //指定线程池大小
  12. }
  13. }

启动类添加注解

  1. @SpringBootApplication
  2. @EnableScheduling//开启定时任务
  3. public class Oms2RtocRtdsocketApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Oms2RtocRtdsocketApplication.class, args);
  6. }
  7. }

使用定时任务

使用注解@Schedule声明这是一个定时任务,Springboot启动会扫描到该注解并标记为定时任务

  1. @Component
  2. public class TestTask {
  3. @Scheduled(cron="*/1 * * * * *")
  4. public void sum2(){
  5. System.out.println("cron 每秒 当前时间:"+new Date());
  6. }
  7. }

使用@Asyn异步执行

这是一个异步任务的方法。如果在类上使用该注解,则该类下所有方法都是异步任务的方法;也可给某方法单独使用该注解。

  1. @Component
  2. @Async
  3. public class AsyncTask {
  4. public void task1() throws InterruptedException{
  5. long begin = System.currentTimeMillis();
  6. Thread.sleep(1000L);
  7. long end = System.currentTimeMillis();
  8. System.out.println("任务1耗时="+(end-begin));
  9. }
  10. public void task2() throws InterruptedException{
  11. long begin = System.currentTimeMillis();
  12. Thread.sleep(2000L);
  13. long end = System.currentTimeMillis();
  14. System.out.println("任务2耗时="+(end-begin));
  15. }
  16. public void task3() throws InterruptedException{
  17. long begin = System.currentTimeMillis();
  18. Thread.sleep(3000L);
  19. long end = System.currentTimeMillis();
  20. System.out.println("任务3耗时="+(end-begin));
  21. }
  22. //获取异步结果
  23. public Future<String> task4() throws InterruptedException{
  24. long begin = System.currentTimeMillis();
  25. Thread.sleep(2000L);
  26. long end = System.currentTimeMillis();
  27. System.out.println("任务4耗时="+(end-begin));
  28. return new AsyncResult<String>("任务4");
  29. }
  30. public Future<String> task5() throws InterruptedException{
  31. long begin = System.currentTimeMillis();
  32. Thread.sleep(3000L);
  33. long end = System.currentTimeMillis();
  34. System.out.println("任务5耗时="+(end-begin));
  35. return new AsyncResult<String>("任务5");
  36. }
  37. public Future<String> task6() throws InterruptedException{
  38. long begin = System.currentTimeMillis();
  39. Thread.sleep(1000L);
  40. long end = System.currentTimeMillis();
  41. System.out.println("任务6耗时="+(end-begin));
  42. return new AsyncResult<String>("任务6");
  43. }
  44. }