SpringBoot最新最详细的定时任务

相信各位小伙伴在项目中经常用到定时任务,下面我总结一下,如何简单使用:

springboot整合定时任务步骤:

1.创建一个类,方法上加入@Scheduled注解
2.在启动类上加入@EnableScheduling注解

  • 首先在pom.xml加入
  
       org.springframework.boot
       spring-boot-devtools
       runtime
   
  • 在Application类加入@EnableScheduling注解
package com.zpy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SpringbootTimingtaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTimingtaskApplication.class, args);
    }
}
  • 创建定时任务类Timingtask
package com.zpy.util;

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

import java.util.Date;

/**
 * @author zpy
 * @description Timingtask
 * @date 2020/03/11 10:56
 */
@Component
public class Timingtask{

    @Scheduled(cron = "0/1 * * * * ?")
    private void test() {
        System.out.println("执行定时任务的时间是:"+new Date());
    }

}

启动即可在控制台输入:

执行定时任务的时间是:xxxxx

注意:@Scheduled(cron = “0/1 * * * * ?”)是每秒执行一次,具体情况根据实际需求更改!

如果帮助到你,麻烦点个赞和留言,谢谢~~~~

你可能感兴趣的:(springboot)