Spring Boot定时任务
在Spring Boot中,可以使用@Scheduled注解来创建定时任务。@Scheduled注解可用于方法级别,用于指定方法在特定时间间隔或特定时间执行。
下面是在Spring Boot中创建定时任务的步骤:
- 在Spring Boot应用程序的类上添加
@EnableScheduling注解,以启用定时任务的支持。
@SpringBootApplication
@EnableScheduling
public class YourApplication {
// ...
}
- 在要执行定时任务的方法上添加
@Scheduled注解,并指定任务的触发时间或时间间隔。
@Component
public class MyTask {
@Scheduled(fixedDelay = 5000) // 每隔5秒执行一次
public void doSomething() {
// 定时任务的逻辑代码
}
}
上面的例子中,doSomething()方法将会在启动后每隔5秒执行一次。
@Scheduled注解还支持其他属性,例如:
fixedRate:指定任务开始的时间间隔,单位为毫秒。fixedDelay:指定任务执行完成后的时间间隔,单位为毫秒。initialDelay:指定任务首次执行的延迟时间,单位为毫秒。cron:使用Cron表达式指定更复杂的任务触发时间。
以下是使用cron属性的示例:
@Component
public class MyTask {
@Scheduled(cron = "0 0/5 * * * ?") // 每隔5分钟执行一次
public void doSomething() {
// 定时任务的逻辑代码
}
}
在上面的例子中,doSomething()方法将会在每个小时的每个第5分钟执行。
请注意,定时任务方法必须是无返回值(void)的,并且没有参数。

浙公网安备 33010602011771号