1、相关知识
2、注解使用
@EnableScheduling:定时任务开关。
@EnableAsync:方法按周期新启动一个线程异步开关。
@Scheduled(cron = "0/5 * * * * ?"):配置定时任务。
@Async:方法按周期新启动一个线程。
3、使用示例
配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@EnableScheduling
@EnableAsync
public class ScheduleConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(50);
return taskScheduler;
}
}
具体定时任务类:
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SchedulDemo {
//@Async
@Scheduled(cron = "0/5 * * * * ?")
public void Test(){
try {
long threadId = Thread.currentThread().getId();
System.out.println("1-start-1,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
Thread.sleep(12*1000);
System.out.println("1-end-1,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
@Async
@Scheduled(cron = "0/5 * * * * ?")
public void Test2(){
try {
long threadId = Thread.currentThread().getId();
System.out.println("1-start-2,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
Thread.sleep(12*1000);
System.out.println("1-end-2,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}