springboot定时任务代码
时间: 2023-10-13 16:20:10 浏览: 80
以下是一个简单的Spring Boot定时任务代码示例:
1. 创建一个名为TaskScheduler的类。
```java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TaskScheduler {
@Scheduled(fixedRate = 1000) // 每隔1秒执行一次
public void task() {
System.out.println("Task executed!");
}
}
```
2. 在pom.xml中添加以下依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
3. 在启动类中添加@EnableScheduling注解。
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 运行程序,每隔1秒钟输出一次“Task executed!”。
以上是一个简单的Spring Boot定时任务代码示例。您可以根据自己的需求进行修改和扩展。
阅读全文
相关推荐


















