Springboot异步处理只要主程序中开启异步处理@EnableScheduling,具体执行使用@Scheduled注解 填写不同的表达式即可,具体demo如下:
1、入口类开启异步调用
package com.chongdian.api;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableScheduling //开启任务调用
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
2、实现方法(参数)
package com.chongdian.api.Task;
import org.springframework.stereotype.Component;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
@Component
public class Scheduled {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@org.springframework.scheduling.annotation.Scheduled(fixedRate = 3000)
public void study(){
System.out.println("现在时间" + dateFormat.format(new Date()));
}
}
结果
3、实现方法(表达式)
package com.chongdian.api.Task;
import org.springframework.stereotype.Component;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
@Component
public class Scheduled {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@org.springframework.scheduling.annotation.Scheduled(cron = "20-50 * * * * ?")
public void study(){
System.out.println("现在时间" + dateFormat.format(new Date()));
}
}
结果