美文网首页
spring定时任务

spring定时任务

作者: guideEmotion | 来源:发表于2019-05-12 20:11 被阅读0次

    一 配置

    多线程存在阻塞问题,所以需要配置线程池

    <task:scheduler id="myScheduler" pool-size="5"/>
    

    详见:spring定时任务详解(@Scheduled注解)

    二 异步

    1.@Async

    详见:https://segmentfault.com/a/1190000015267976
    补充:

    1. @Async会导致fixedDelay失效
        @Async
        @Scheduled(initialDelay=1000,fixedDelay=2000)
        public void test2() {
            logger.info(Thread.currentThread().getName()+"===test2 start");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            logger.info(Thread.currentThread().getName()+"===test2 end");
        }
    
    

    结果:间隔两秒执行

    2019-04-25 23:19:28.381  INFO 19272 --- [cTaskExecutor-1] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-1===test2 start
    2019-04-25 23:19:30.371  INFO 19272 --- [cTaskExecutor-2] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-2===test2 start
    2019-04-25 23:19:32.372  INFO 19272 --- [cTaskExecutor-3] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-3===test2 start
    2019-04-25 23:19:33.381  INFO 19272 --- [cTaskExecutor-1] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-1===test2 end
    2019-04-25 23:19:34.374  INFO 19272 --- [cTaskExecutor-4] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-4===test2 start
    2019-04-25 23:19:35.372  INFO 19272 --- [cTaskExecutor-2] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-2===test2 end
    2019-04-25 23:19:36.375  INFO 19272 --- [cTaskExecutor-5] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-5===test2 start
    2019-04-25 23:19:37.373  INFO 19272 --- [cTaskExecutor-3] com.example.demo.task.Mytask             : SimpleAsyncTaskExecutor-3===test2 end
    
    1. @Async会导致fixRate可以并发执行

    2. springboot中的多线程并行应用

    Spring定时任务并行(异步)处理

    2.1 SchedulingConfigurer

    1.实现动态定时任务

        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.addFixedRateTask(() -> System.out.println("执行定时任务1: " + new Date()), 1000);
            TriggerTask triggrtTask = new TriggerTask( // 任务内容.拉姆达表达式
                    () -> {System.out.println("执行定时任务2: " + new Date());},
                    // 设置触发器,这里是一个拉姆达表达式,传入的TriggerContext类型,返回的是Date类型
                    triggerContext -> {
                        // 2.3 返回执行周期(Date)
                        return new CronTrigger("*/2 * * * * ?").nextExecutionTime(triggerContext);
                    });
     
            taskRegistrar.addTriggerTask(triggrtTask);
        }
    

    参考:https://cloud.tencent.com/developer/article/1362794

    2.实现并行,设置线程池

    import org.springframework.scheduling.TaskScheduler; 
    import org.springframework.scheduling.annotation.AsyncConfigurer; 
    import org.springframework.scheduling.annotation.EnableAsync; 
    import org.springframework.scheduling.annotation.EnableScheduling; 
    import org.springframework.scheduling.annotation.SchedulingConfigurer; 
    import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 
    import org.springframework.scheduling.config.ScheduledTaskRegistrar;
    
    @Configuration 
    @EnableScheduling 
    @EnableAsync( mode = AdviceMode.PROXY, proxyTargetClass = false, order=Ordered.HIGHEST_PRECEDENCE ) 
    @ComponentScan( basePackages = “hello” ) 
    public class RootContextConfiguration implements AsyncConfigurer, SchedulingConfigurer { 
    
    @Bean 
    public ThreadPoolTaskScheduler taskScheduler() { 
      ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); 
      scheduler.setPoolSize(20); 
      scheduler.setThreadNamePrefix(“task-“); 
      scheduler.setAwaitTerminationSeconds(60); 
      scheduler.setWaitForTasksToCompleteOnShutdown(true); 
      return scheduler; 
    }
    
    @Override 
    public Executor getAsyncExecutor() { 
      Executor executor = this.taskScheduler(); 
      return executor; 
    }
    
    @Override 
    public void configureTasks(ScheduledTaskRegistrar registrar) { 
      TaskScheduler scheduler = this.taskScheduler(); 
      registrar.setTaskScheduler(scheduler); 
    } 
    } 
    

    2.2 AsyncConfigurer

    主要也是配置线程池
    SpringBoot 线程池配置 实现AsyncConfigurer接口

    相关文章

      网友评论

          本文标题:spring定时任务

          本文链接:https://www.haomeiwen.com/subject/jwztnqtx.html