Spring后端技术

Spring快速开启计划任务

2017-08-24  本文已影响16人  Java技术栈

Spring3.1开始让计划任务变得非常简单,只需要几个注解就能快速开启计划任务的支持。

@EnableScheduling

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Import(SchedulingConfiguration.class)

@Documented

public@interfaceEnableScheduling{

}

@EnableScheduling、@Configuration两个同时使用开启计划任务支持。

importorg.springframework.context.annotation.Configuration;

importorg.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling

@Configuration

publicclassTaskConfiguration{

}

@Scheduled

在要使用计划任务的方法上使用Scheduled,fixedRate表示固定频率,cron即自定义执行表达式,更多用法参考注解@Scheduled参数。

@Service

publicclassTestTask{

protectedLoggerlogger=LoggerUtils.getLogger(this);

@Scheduled(fixedRate=5000)

publicvoidrunPerFiveSeconds(){

logger.info("fix");

}

@Scheduled(cron="0/10 * 9 * * ?")

publicvoidrunCron(){

logger.info("cron");

}

}

上一篇下一篇

猜你喜欢

热点阅读