3.3 Spring高级话题: 计划任务
3.3 Spring 计划任务
1.Spring3.1开始,计划任务开始异常的简单
2.配置
2.1 首先通过配置类注解@EnableScheduling来开启计划任务的支持
2.2 然后在需要计划任务的方法上注解@Scheduled,声明这个是一个计划
配置过程
1.通过@EnableScheduling注解开启计划任务支持
2.通过@Scheduled注解表明方法是计划方法
1.java配置
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("com.sgx.inspect.bug")
@EnableScheduling
public class ScheduleConfigurate {
}
2.使用@Async注解
@Service
public class ScheduleService {
@Scheduled(fixedRate = 5000)
public void scheduleTask() {
System.out.println("5M秒执行一次:" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
3.测试使用
import com.sgx.inspect.bug.service.ScheduleConfigurate;
import com.sgx.inspect.bug.service.ScheduleService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main2 {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduleConfigurate.class);
ScheduleService bean = context.getBean(ScheduleService.class);
}
}