在线文字转语音网站:无界智能 aiwjzn.com

Java使用Spring Scheduler实现一个简单的定时任务

Java使用Spring Scheduler实现一个简单的定时任务

依赖类库的Maven坐标: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 实现完整的样例并写出完整Java代码: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; @SpringBootApplication @EnableScheduling public class SchedulerApplication { public static void main(String[] args) { SpringApplication.run(SchedulerApplication.class, args); } @Scheduled(fixedRate = 5000) // 每隔5秒执行一次 public void task() { System.out.println("定时任务执行"); } } 总结:以上是一个简单的使用Spring Scheduler实现定时任务的样例。使用Spring Scheduler需要在应用入口类上添加注解@EnableScheduling,并在定时任务的方法上添加注解@Scheduled,并指定任务的执行时间策略,如fixedRate表示每隔固定时间执行一次任务。