zoukankan      html  css  js  c++  java
  • boot中的Scheduling定时器使用笔记

    使用注解@Scheduled(单线程)

    PS:类上或者启动类上必须加上@EnableScheduling

     @Scheduled(cron = "0/2 * * * * *")
        public void timerBreakCat(){
            LocalDateTime localDateTime = LocalDateTime.now();
            System.out.println("Cat当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss")));
        }
    
        @Scheduled(cron = "0/2 * * * * *")
        public void timerBreakDog(){
            LocalDateTime localDateTime = LocalDateTime.now();
            System.out.println("Dog当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss")));
        }

    改为多线程的俩种比较简单方式

    使用注解@EnableAsync和@Async

    创建线程池

    @Configurable
    public class ScheduleConfig {
    
        @Bean
        public TaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(10);
            return scheduler;
        }
    }

    实现SchedulingConfigurer接口(并行线程)

    @Configuration
    @Slf4j
    public class DemoTask implements SchedulingConfigurer {
    
        private static String cron = "0/5 * * * * ?";
    
        @Async
        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.addTriggerTask(
                    //1.添加任务内容(Runnable)
                    () -> new Thread(() -> {
                        try {
                          // TODO 任务内容
                            log.info("执行时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }).start(),
                    //2.设置执行周期(Trigger)
                    triggerContext -> {
                        //随机生成cron
                        String temp = ((int) (Math.random() * 7+3))+"";
                        cron = "0/"+temp+" * * * * ?";
                        //返回执行周期(Date)
                        return new CronTrigger(cron).nextExecutionTime(triggerContext);
                    }
            );
        }
    }

    cron表达式

    生成器网站 http://www.bejson.com/othertools/cron/

  • 相关阅读:
    如何通过地址转换为WGS经纬度
    Oracle动态创建时间分区,以及Oracle12c中快速创建自增列
    asp.net微信jsapi支付
    asp.net关于如何准许api跨域访问
    ajax调用天气接口
    git补充(命令)转自https://github.com/Wasdns/github-example-repo
    git补充(关于pull request)转自知乎
    Linux基础笔记
    git前期准备
    MVC设计模式
  • 原文地址:https://www.cnblogs.com/21-Gram/p/11321493.html
Copyright © 2011-2022 走看看