spring boot: 计划任务@ EnableScheduling和@Scheduled
spring boot: 计划任务@ EnableScheduling和@Scheduled
@Scheduled中的参数说明
1 2 3 4 5 6 7 |
|
常用Cron表达式( 秒/分/时/日/月/周/年 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
实例:
service
package test.scheduler;
//时间处理,时间格式化
import java.util.Date;
import java.text.SimpleDateFormat;
//spring计划任务声明(针对方法声明)
import org.springframework.scheduling.annotation.Scheduled;
//spring组件声明
import org.springframework.stereotype.Service;
//组件什么
@Service
public class SchedulerService {
//创建日期模板
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH::MM::ss");
//每5秒钟执行一次
@Scheduled(fixedRate = 5000)
public void reportCurrentTime()
{
System.out.println("每五秒执行一次: " + dateFormat.format( new Date() ));
}
//按照cron属性指定执行时间:秒分时
@Scheduled(cron = "0 34 18 ? * *")
public void fixTimeExecution()
{
System.out.println("在指定的时间内执行: " + dateFormat.format( new Date()) );
}
}
config
package test.scheduler;
//自动引入包
import org.springframework.context.annotation.ComponentScan;
//配置类声明
import org.springframework.context.annotation.Configuration;
//计划任务类声明
import org.springframework.scheduling.annotation.EnableScheduling;
//配置类声明
@Configuration
//自动引入包
@ComponentScan("ch2.scheduler")
//通过@EnableScheduling开启对计划任务的支持
@EnableScheduling
public class TaskSchedulerConfig {
}
main
package test.scheduler;
//引入容器
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args)
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
//SchedulerService schedulerService = context.getBean(SchedulerService.class);
}
}