???
实例如下:
?
class="java">package com.zgw.taskscheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class SchedulerTaskService { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); /** * 1. fixedRate每隔固定时间执行 * 2.@Scheduled声明是一个定时任务 */ @Scheduled(fixedRate = 3000) public void reportCurrentTime() { System.out.println("每隔3秒执行一次 " + dateFormat.format(new Date())); } @Scheduled(cron = "0 53 21 ? * *" ) // public void fixTimeExecution(){ System.out.println("在指定时间 (每天21:53)" + dateFormat.format(new Date())+"执行"); } }
?
2.配置类
package com.zgw.taskscheduler; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @ComponentScan("com.zgw.taskscheduler") @EnableScheduling //开启对计划任务的支持 public class TaskSchedulerConfig{ }
?
3.测试类
?
package com.zgw.taskscheduler; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestScheduler { public static void main(String[] args) { //使用AnnotationConfigApplicationContext作为spring容器, //接收输入一个配置类作为参数 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class); } }
?
运行结果:
?
?
?
?