Springboot 创建定时任务

使用Springboot创建定时任务

  • 使用注解@EnableScheduling开启定时任务,会自动扫描
  • 定义@Component作为组件被容器扫描
  • cron表达式生成地址:http://cron.qqe2.com/

示例:
主线程

@SpringBootApplication
// 扫描所有需要的包,包含一些自用的工具类包所在的路径
@ComponentScan(basePackages = {"com.yxc.test"})
// 开启定时任务
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}

Compent(1)

@Component
public class SchedualTask {
private static final SimpleDateFormat dateFormate = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
// 定义每过n秒执行一次(假设n=5)
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("What The Time Now? It's " + dateFormate.format(new Date()));
}
}

结果

What The Time Now? It's 2018-10-16 00:30:35
What The Time Now? It's 2018-10-16 00:30:40
What The Time Now? It's 2018-10-16 00:30:45
What The Time Now? It's 2018-10-16 00:30:50
What The Time Now? It's 2018-10-16 00:30:55
What The Time Now? It's 2018-10-16 00:31:00
What The Time Now? It's 2018-10-16 00:31:05
What The Time Now? It's 2018-10-16 00:31:10
What The Time Now? It's 2018-10-16 00:31:15
What The Time Now? It's 2018-10-16 00:31:20

Compent(2)

@Component
public class SchedualTask {
private static final SimpleDateFormat dateFormate = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
/**
* 使用cron表达式
* 周期从1分钟1到10秒
*/
@Scheduled(cron = "1-10 * * * * ? ")
public void reportCurrentTime() {
System.out.println("What The Time Now? It's " + dateFormate.format(new Date()));
}
}

你可能感兴趣的:(Springboot 创建定时任务)