springboot定时任务注解
时间: 2023-10-19 16:06:06 浏览: 45
Spring Boot中的定时任务注解是`@Scheduled`。通过在方法上添加`@Scheduled`注解,可以指定方法在特定时间间隔或固定时间执行。
以下是一个使用`@Scheduled`注解的例子:
```java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduledTask {
@Scheduled(fixedRate = 5000) // 每5秒执行一次
public void myTask() {
// 执行定时任务的逻辑
}
}
```
在上面的例子中,`myTask()`方法被注解为一个定时任务。通过设置`fixedRate`参数为5000,表示该方法将每隔5秒执行一次。
除了`fixedRate`,`@Scheduled`注解还支持其他参数来定义定时任务的执行时间,例如:
- `fixedDelay`:表示上一次执行完成后延迟固定时间再执行。
- `initialDelay`:表示首次执行延迟时间。
- `cron`:使用Cron表达式定义更复杂的定时任务。
需要注意的是,为了使`@Scheduled`注解生效,还需在Spring Boot主程序类上添加注解`@EnableScheduling`。
这就是在Spring Boot中使用定时任务注解的方式。希望对你有所帮助!如果有任何疑问,请随时提问。