Spring中实现定时任务
程序员文章站
2022-05-07 16:45:08
...
- spring中通过@EnableScheduling来开启对定时任务的支持
- 然后通过@Scheduled声明,它支持多种类型的定时任务,包含cron,fixDelay,fixRate等
实例如下:
- 定时任务执行类
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); } }
运行结果:
上一篇: 中文乱码解决的4种方式
下一篇: springboot中创建定时任务