1. 首页
  2. 软件开发
  3. Spring Boot——定时任务和调度

Spring Boot——定时任务和调度

  • 发布于 2024-08-17
  • 0 次阅读

Spring Boot内置了对定时任务和调度的支持,可以使用 @Scheduled 注解来创建定时任务。这使得在Spring Boot应用程序中执行周期性任务变得非常简单。

  1. 配置定时任务 :在Spring Boot应用程序中配置定时任务,需要在配置类上添加 @EnableScheduling 注解。这样Spring容器就会识别 @Scheduled 注解并按照指定的时间间隔执行任务。

  2. 创建定时任务方法 :在需要定时执行的方法上添加 @Scheduled 注解,并指定执行的时间间隔、固定延迟或固定速率等参数。

详细步骤如下:

首先,在配置类中添加 @EnableScheduling 注解来启用定时任务支持:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class ScheduledTaskConfig {
   
}

然后,创建一个包含定时任务方法的服务类:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledTaskService {
   

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void scheduledTask() {
   
        System.out.println("定时任务执行:" + new Date());
    }
}

最后,在控制器中调用定时任务方法:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ScheduledTaskController {
   

    @Autowired
    private ScheduledTaskService scheduledTaskService;

    @GetMapping("/startTask")
    public String startScheduledTask() {
   
        scheduledTaskService.scheduledTask();
        return "定时任务已启动";
    }
}

通过上述步骤,当访问 /startTask 端点时,定时任务方法将会被执行,每隔5秒输出一条日志信息。这样可以实现在Spring Boot应用程序中定时执行任务的功能,非常适合需要周期性执行某些操作的场景。

原文链接: https://blog.csdn.net/2401_82884096/article/details/138318827