1、启动类加注解@EnableScheduling
package cn.sunline.insd.sso.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(scanBasePackages = { "${app.scan.packages}" })
@EnableEurekaClient
@EnableHystrix
@EnableCircuitBreaker
@EnableScheduling
public class InsdSimpleWebApplication {
public static void main(String[] args) {
SpringApplication.run(InsdSimpleWebApplication.class, args);
}
}
2、编写测试类,需要@Component管理,需要执行的定时任务加注解@Scheduled(cron="cron表达式")
package cn.sunline.insd.sso.scheud;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTest {
private static final Logger logger = Logger.getLogger(ScheduledTest.class);
@Scheduled(cron="*/5 * * * * ?")
public void executeFileDownLoadTask() {
// 间隔5秒,执行任务
Thread current = Thread.currentThread();
System.out.println("定时任务1:"+current.getId());
logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
}
}
3、执行效果