美文网首页
定时任务

定时任务

作者: BySjm | 来源:发表于2020-01-11 20:13 被阅读0次

    SpringTask

    使用

    • 在SpringBoot的引导类上加开启定时任务的注解@EnableScheduling

    实例代码:每秒输出当前时间

    第一种写法
    import lombok.extern.slf4j.Slf4j;
    import org.joda.time.DateTime;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    @Slf4j
    public class TaskTest {
        @Scheduled(cron = "0/1 * * * * ?")
        public void test() {
            log.debug(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        }
    }
    
    第二种写法
    import lombok.extern.slf4j.Slf4j;
    import org.joda.time.DateTime;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    @Slf4j
    public class TaskTest {
        @Scheduled(fixedDelay = 1000)
        //@Scheduled(fixedDelayString = "1000")
        public void test2() {
            log.debug(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        }
    }
    
    第三种写法
    import lombok.extern.slf4j.Slf4j;
    import org.joda.time.DateTime;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    @Slf4j
    public class TaskTest {
        @Scheduled(fixedRate = 1000)
        public void test3() {
            log.debug(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        }
    }
    

    @Scheduled(fixedDelay = 1000)和@Scheduled(fixedRate = 1000)的区别

    • fixedDelay积压的任务不会执行,任务会丢失。fixedRate会执行积压的任务,任务不会丢失
    • cron表达式的写法默认和fixedDelay一样。积压的任务不会执行,任务会丢失

    任务线程池

    spring
      task:
        scheduling:
           pool:
             size: 10
    

    相关文章

      网友评论

          本文标题:定时任务

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