美文网首页
Spring Boot任务

Spring Boot任务

作者: 虫儿飞ZLEI | 来源:发表于2019-03-04 20:28 被阅读0次

    1. 异步任务

    1.1 开启异步注解功能

    @EnableAsync //开启异步注解功能
    加在启动类的上面

    1.2 使用

    @Service
    public class AsyncService {
    
        //告诉Spring这是一个异步方法
        @Async
        public void hello(){
            System.out.println("处理数据中...");
        }
    }
    
    

    调用:

        @Autowired
        AsyncService asyncService;
    
        @GetMapping("/hello")
        public String hello(){
            //这个hello方法的执行,spring会自己开线程池去操作
            asyncService.hello();
            //其他的按照正常执行
            return "success";
        }
    

    2. 定时任务

    2.1 开启基于注解的定时任务

    @EnableScheduling //开启基于注解的定时任务
    加在启动类的上面

    2.2 使用

    @Service
    public class ScheduledService {
    
        /**
         * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
         * 0 * * * * MON-FRI
         *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
         *  【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
         *  【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
         *  【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
         *  【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
         */
       // @Scheduled(cron = "0 * * * * MON-SAT")
        //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
       // @Scheduled(cron = "0-4 * * * * MON-SAT")
        @Scheduled(cron = "0/4 * * * * MON-SAT")  //每4秒执行一次
        public void hello(){
            System.out.println("hello ... ");
        }
    }
    

    cron 有在线生成网站,可自行百度

    相关文章

      网友评论

          本文标题:Spring Boot任务

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