springboot2 定时任务 task

  1. pom.xml 引入 web 依赖,需要用到 spring 的任务类
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 入口类上加@EnableScheduling注解,激活定时任务
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
    public static void main(String[] args) {
        SpringApplication.run(SchedulingApplication.class, args);
    }
}
  1. 类上加@Component注解,被扫描到。方法上加@Scheduled注解,设置定时
@Component
public class TestTask {
    // 3秒一次
    @Scheduled(fixedRate = 3000)
    public void doing() {
        System.out.println("3秒一次");
    }

    // 6 秒一次:秒 分 时 日 月 周
    @Scheduled(cron = "*/6 * * * * *")
    public void doing2() {
        System.out.println("6秒一次");
    }
}

参考:http://www.fengyunxiao.cn

猜你喜欢

转载自blog.csdn.net/m0_37202351/article/details/82763303
今日推荐