springboot之定时任务操作流程

一.创建定时任务类,类上添加注解@EnableScheduling,任务方法上添加@Scheduled(cron = “0/50 * * * * ?”)

@Component
@EnableScheduling
public class ScheduledTask {

    @Autowired
    private RabbitService rabbitService;

    /**
     * 每天8点执行 提醒就诊
     */
    //@Scheduled(cron = "0 0 8 * * ?")
    @Scheduled(cron = "0/50 * * * * ?")//50秒触发一次
    public void task1() {
    //任务内容
        System.out.println(new Date().toLocaleString());
      
    }
}

cron表达式控制定时任务触发的时间
通过不同的cron来指定触发时间

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,通过`@RestController`注解执行定时任务管理的业务流程可以按照以下步骤进行: 1. 首先,确保在Spring Boot项目的pom.xml文件中添加了以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 创建一个任务管理类,该类负责定义定时任务的具体执行逻辑。在该类上添加`@Component`注解,将其作为一个组件进行注册。 ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TaskManager { // 每隔5秒执行一次任务 @Scheduled(fixedRate = 5000) public void task() { // 任务逻辑代码 System.out.println("执行定时任务"); } } ``` 在上述代码中,我们定义了一个名为`task`的方法,并使用`@Scheduled`注解指定了任务的执行频率为每隔5秒执行一次。 3. 创建一个控制器类,使用`@RestController`注解声明为一个RESTful接口,并注入任务管理类的实例。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TaskController { @Autowired private TaskManager taskManager; @GetMapping("/startTask") public String startTask() { // 启动定时任务 return "定时任务已启动"; } @GetMapping("/stopTask") public String stopTask() { // 停止定时任务 return "定时任务已停止"; } } ``` 在上述代码中,我们使用`@RestController`注解将类声明为一个RESTful接口。在`startTask`和`stopTask`方法中,可以调用任务管理类的相关方法来启动和停止定时任务。 4. 在Spring Boot应用程序的启动类上添加`@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); } } ``` 通过以上步骤,你可以通过访问`/startTask`和`/stopTask`接口来触发定时任务的启动和停止。当调用`/startTask`接口时,定时任务将开始执行;当调用`/stopTask`接口时,定时任务将停止执行。 注意:为了能够使用定时任务功能,需要在Spring Boot应用程序的配置类或启动类上添加`@EnableScheduling`注解。这样,Spring Boot会自动扫描并执行被`@Scheduled`注解标记的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值