springboot使用SpringTask实现定时任务

 

SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用。

 

只需要在配置类中添加一个@EnableScheduling注解即可开启SpringTask的定时任务能力。

/**
 * 定时任务配置
 * Created by xc on 190830
 */
@Configuration
@EnableScheduling
public class SpringTaskConfig {
}

 

添加OrderTimeOutCancelTask来执行定时任务

@Component
public class OrderTimeOutCancelTask {

    private Logger LOGGER = LoggerFactory.getLogger(OrderTimeOutCancelTask.class);

    /**
     * cron表达式:Seconds Minutes Hours DayofMonth Month DayofWeek [Year]
     */
    @Scheduled(cron = "0/15 * * * * ?")
    private void cancelTimeOutOrder() {
        LOGGER.info("定时任务OrderTimeOutCancelTask");
    }

    @Scheduled(fixedDelay = 100000) // fixedDelay = 1000表示在当前任务执行结束1秒后开启另一个任务
    public void fixedDelay() {
        System.out.println("fixedDelay:" + new Date());
    }

    @Scheduled(fixedRate = 200000) // fixedRate = 2000表示在当前任务开始执行2秒后开启另一个定时任务
    public void fixedRate() {
        System.out.println("fixedRate:" + new Date());
    }

    @Scheduled(initialDelay = 100000, fixedRate = 200000) // initialDelay = 1000则表示首次执行的延迟时间
    public void initialDelay() {
        System.out.println("initialDelay:" + new Date());
    }

    @Scheduled(cron = "0 * * * * ?") // 表示该定时任务每分钟执行一次
    public void cron() {
        System.out.println("cron:" + new Date());
    }
    


}

  

posted @ 2019-08-30 16:25  草木物语  阅读(1032)  评论(0编辑  收藏  举报