首页 > 代码库 > Spring Boot教程11——计划任务
Spring Boot教程11——计划任务
从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled声明这是一个计划任务。
Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRatedeng。
示例
1>.计划任务执行类
package com.wisely.highlight_spring4.ch3.taskscheduler;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;@Servicepublic class ScheduledTaskService { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行 public void reportCurrentTime() { System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date())); } @Scheduled(cron = "0 28 11 ? * *" ) //使用cron属性可按指定时间执行,本例指的是11点28分执行;cron是UNIX和类UNIX(如Linux)系统下的定时任务 public void fixTimeExecution(){ System.out.println("在指定时间 " + dateFormat.format(new Date())+"?执行"); }}
2>.配置类
package com.wisely.highlight_spring4.ch3.taskscheduler;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;@Configuration@ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")@EnableScheduling //开启对计划任务的支持public class TaskSchedulerConfig {}
3>.运行
package com.wisely.highlight_spring4.ch3.taskscheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class); }}
Spring Boot教程11——计划任务
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。