- 启动类加注解,发现定时任务注解
@Slf4j
@SpringBootApplication
@EnableScheduling
public class CommonApplication {
public static void main(String[] args) {
log.info("application start...");
SpringApplication.run(CommonApplication.class, args);
}
}
- 配置定时任务
- 单线程任务,同一个线程中串行执行所有任务。这样会存在问题。当线程阻塞在某一个任务中,其他任务都会被阻塞。
使用@Scheduled注解,cron表达式网上可以找
@Service
public class ScheduleImpl {
@Scheduled(cron="0/2 * * * * ? ")
public void execute(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********A任务每2秒执行一次进入测试"+Thread.currentThread().getName());
}
@Scheduled(cron="0/3 * * * * ? ")
public void executetwo(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********B任务每3秒执行一次进入测试"+Thread.currentThread().getName());
}
@Scheduled(cron="0/4 * * * * ? ")
public void executethr(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********C任务每4秒执行一次进入测试"+Thread.currentThread().getName());
}
@Scheduled(cron="0/5 * * * * ? ")
public void executefour() throws InterruptedException {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********D任务每5秒执行一次进入测试"+Thread.currentThread().getName());
Thread.sleep(5000);
}
}
- 线程池执行定时任务,具体使用线程池在我的文章上一节里面有。这样使用线程池就可以避免线程阻塞
@Service
public class ScheduleImpl {
@Scheduled(cron="0/2 * * * * ? ")
public void execute(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********A任务每2秒执行一次进入测试"+Thread.currentThread().getName());
}
@Scheduled(cron="0/3 * * * * ? ")
public void executetwo(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********B任务每3秒执行一次进入测试"+Thread.currentThread().getName());
}
@Scheduled(cron="0/4 * * * * ? ")
public void executethr(){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********C任务每4秒执行一次进入测试"+Thread.currentThread().getName());
}
@Async("executor")
@Scheduled(cron="0/5 * * * * ? ")
public void executefour() throws InterruptedException {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(DateTime.now())+"*********D任务每5秒执行一次进入测试"+Thread.currentThread().getName());
Thread.sleep(5000);
}
}
- 启动项目,将会自动执行定时任务。注意,单元测试只会请求一次,不会执行定时任务。