定时任务
定时任务线程池
@Configuration
//开启异步事件的支持
@EnableAsync
public class ScheduledConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(10); //指定线程池大小
}
}
启动类添加注解
@SpringBootApplication
@EnableScheduling//开启定时任务
public class Oms2RtocRtdsocketApplication {
public static void main(String[] args) {
SpringApplication.run(Oms2RtocRtdsocketApplication.class, args);
}
}
使用定时任务
使用注解@Schedule声明这是一个定时任务,Springboot启动会扫描到该注解并标记为定时任务
@Component
public class TestTask {
@Scheduled(cron="*/1 * * * * *")
public void sum2(){
System.out.println("cron 每秒 当前时间:"+new Date());
}
}
使用@Asyn异步执行
这是一个异步任务的方法。如果在类上使用该注解,则该类下所有方法都是异步任务的方法;也可给某方法单独使用该注解。
@Component
@Async
public class AsyncTask {
public void task1() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(1000L);
long end = System.currentTimeMillis();
System.out.println("任务1耗时="+(end-begin));
}
public void task2() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
long end = System.currentTimeMillis();
System.out.println("任务2耗时="+(end-begin));
}
public void task3() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(3000L);
long end = System.currentTimeMillis();
System.out.println("任务3耗时="+(end-begin));
}
//获取异步结果
public Future<String> task4() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
long end = System.currentTimeMillis();
System.out.println("任务4耗时="+(end-begin));
return new AsyncResult<String>("任务4");
}
public Future<String> task5() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(3000L);
long end = System.currentTimeMillis();
System.out.println("任务5耗时="+(end-begin));
return new AsyncResult<String>("任务5");
}
public Future<String> task6() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(1000L);
long end = System.currentTimeMillis();
System.out.println("任务6耗时="+(end-begin));
return new AsyncResult<String>("任务6");
}
}