`

SpringBoot-第十章 SpringBoot整合定时任务和异步任务处理

阅读更多

定时任务

@Component
public class TestTask {

    //@Scheduled(fixedRate = 2000)//两秒执行一次(从上一次开始计算2秒后)
    //@Scheduled(fixedDelay = 2000)//每次执行间隔两秒
    //@Scheduled(cron="*/2 * * * * *")//每次执行间隔两秒
    @Scheduled(fixedDelayString = "2000")//每次执行间隔两秒,这个参数可以同配置文件配置
    public void sum() throws Exception
    {
        Thread.sleep(4000);
        System.out.println("当前时间:"+new Date());
    }
}

 

异步任务

@Component
@Async
public class AsyncTask {

    public void task1() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(1000);
        Long end = System.currentTimeMillis();
        System.out.println("任务1耗时:"+(end-start));
    }
    public void task2() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(2000);
        Long end = System.currentTimeMillis();
        System.out.println("任务2耗时:"+(end-start));
    }
    public void task3() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(3000);
        Long end = System.currentTimeMillis();
        System.out.println("任务3耗时:" + (end - start));
    }
    public Future<String> task4() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(1000);
        Long end = System.currentTimeMillis();
        System.out.println("任务4耗时:"+(end-start));
        return new AsyncResult<String>("任务4结束");
    }
    public Future<String> task5() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(2000);
        Long end = System.currentTimeMillis();
        System.out.println("任务5耗时:"+(end-start));
        return new AsyncResult<String>("任务5结束");
    }
    public Future<String> task6() throws InterruptedException {
        Long start = System.currentTimeMillis();
        Thread.sleep(3000);
        Long end = System.currentTimeMillis();
        System.out.println("任务6耗时:"+(end-start));
        return new AsyncResult<String>("任务6结束");
    }

}

调用异步任务:

@RestController
@RequestMapping("/api/v1/task")
public class MyTaskController {

    @Autowired
AsyncTask aTask;
    @RequestMapping("/async")
    public void doTask() throws InterruptedException {
        long start = System.currentTimeMillis();
        aTask.task1();
        aTask.task2();
        aTask.task3();
        Future<String> t4 = aTask.task4();
        Future<String> t5 = aTask.task5();
        Future<String> t6 = aTask.task6();
        for(;;)
        {
//            if(aTask.task4().isDone()&&aTask.task5().isDone()&&aTask.task6().isDone())
if(t4.isDone()&&t5.isDone()&&t6.isDone())
            {
                break;
            }
        }
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.print("请求耗时:"+(end-start));

    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics