【SpringBoot基础】Schedule 计划任务 注解实现
内容概要
学习计划任务注解实现,写个Demo方便以后使用
文件结构
环境jar包
jdk: jdk1.8.0_121(32位)
pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.10.RELEASE</version>
</dependency>
计划任务服务设置 ScheduleTaskService
package com.Schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class ScheduledTaskService {
//时间显示模板
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000) //间隔五秒
public void printTime(){
System.out.println("每隔五秒钟执行一次:"+dateFormat.format(new Date()));
}
@Scheduled(cron ="0 0 10 ? * *")//Cron表达式 每天10:00:00执行
public void printOnTime(){
System.out.println("在指定时间执行:"+dateFormat.format(new Date()));
}
}
计划任务配置类TaskScheduleConfig
package com.Schedule;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan("com.Schedule")
@EnableScheduling //启动计划任务服务
public class ScheduledConfig {
}
测试类 Main
package com.Schedule;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.scheduling.config.ScheduledTask;
public class Main {
public static void main(String [] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ScheduledConfig.class);
ScheduledTaskService bean = applicationContext.getBean(ScheduledTaskService.class);
}
}