当前位置: 代码迷 >> 综合 >> springboot-定时任务-@Scheduled
  详细解决方案

springboot-定时任务-@Scheduled

热度:74   发布时间:2023-12-15 11:41:37.0

springboot 可以使用@Scheduled(fixedRate=1000) 在方法前面设置该方法为一个定时方法,表示每1秒执行一次。而且一直执行下去,

需要在App.java 中配置开启定时任务注解 @EnableScheduling 

在定时任务类上面,使用了@Component注解,这样,当App.java中配置了扫描包,将生成该组件存在spring容器中。当bean对象生成后就会调用该类中的定时方法。

App.java

package com.anlysqx.app;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;@EnableAutoConfiguration
@ComponentScan(basePackages={"com.anlysqx.controller","com.anlysqx.schedualtask","com.anlysqx.aop","com.anlysqx.service"})
@MapperScan(basePackages={"com.anlysqx.dao"})
@EnableScheduling //开启定时任务注解
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}


SchedualTask1.java

package com.anlysqx.schedualtask;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Component
public class SchedualTack1 {@Scheduled(fixedRate=1000)@ResponseBodypublic String refreshTask(){System.out.println("schedule");return new Date().toString();}}