通过在配置类上添加注解@EnableScheduling来开启对计划任务的支持,然后在计划任务的方法上注解@Scheduled,声明这是一个定时任务。
Spring通过@Scheduled支持多种类型计划任务,包含cron,fixDelay,fixRate.
一:定时任务类
import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledTaskService { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) //1声明该方法是定时任务,每个5秒执行一次 public void reportCurrentTime() { System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date())); } @Scheduled(cron = "0 28 11 ? * *" ) //2.每天11点28分执行 public void fixTimeExecution(){ System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行"); } }
二:配置类:
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @ComponentScan("com.flysun.taskscheduler") @EnableScheduling //开启对定时任务的执行 public class TaskSchedulerConfig { }
三:运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class); } }