Spring Boot 整合定时任务

1. 在 SpringBoot 主类上使用 @EnableScheduling 开启定时调度任务

package com.codingos.springbootdemo;

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

@SpringBootApplication
// 开启定时任务
@EnableScheduling
public class SpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemoApplication.class, args);
	}
}

2. 创建定时任务类

注意类上使用 @Component 注解,方法上使用 @Scheduled 注解

可以使用 cron 表达式

package com.codingos.springbootdemo.task;

import java.text.SimpleDateFormat;
import java.util.Date;

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

@Component
public class TestTask {
	
	private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
	
	@Scheduled(fixedRate = 3000)
	public void reportCurrentTime() {
		System.out.println("现在时间" + SIMPLE_DATE_FORMAT.format(new Date()));
	}
}

猜你喜欢

转载自my.oschina.net/u/1411151/blog/2877239