java定时任务TimerTask与scheduleAtFixedRate

TimerTask

使用demo,当任务的执行时间大于period time(周期时间)的时候,会发现,两次任务之间的间隔时间其实是任务的执行时间,period time并没有生效.(类似单线程被阻塞了,虽然到达下一次任务的运行时间了,但是因为单线程只能等上一次的任务运行完成后才能运行下一次任务).

public String testTimerTask(){
    
    
    Timer timer = new Timer();
    System.out.println(LocalDateTime.now());
    timer.schedule(new TimerTask() {
    
    
        @Override
        public void run() {
    
    
            System.out.println("任务开始 time: " + LocalDateTime.now());
            System.out.println("当前的num: " + timeService.num);
            try {
    
    
                Thread.sleep(5000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            System.out.println("任务结束 time: " + LocalDateTime.now());
            timeService.numCalc();

        }
    }, 2000, 3000);//2000表示第一次执行任务延迟时间,3000 表示以后每隔多长时间执行一次run里面的任务

    //停止定时器
    //timer.cancel();
    return "success";
}

在这里插入图片描述

testScheduleAtFixedRate(推荐比较稳定)

如果任务的执行时间,大于两次任务之间的间隔,那么实际上两次任务的执行间隔时间为单个任务的执行时间

public String testScheduleAtFixedRate(){
    
    
    ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
    scheduled.scheduleAtFixedRate(new Runnable() {
    
    
        @Override
        public void run() {
    
    
            try {
    
    
                System.out.println("任务开始 time: " + LocalDateTime.now());
                System.out.println("当前的num: " + timeService.num);
                Thread.sleep(5000);
                System.out.println("任务结束 time: " + LocalDateTime.now());
                timeService.numCalc();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }, 0, 3000, TimeUnit.MILLISECONDS);//0 表示首次执行任务的延迟时间,3000 表示每次执行任务的间隔时间,TimeUnit.MILLISECONDS执行的时间间隔数值单位

    //停止定时器
    //scheduled.shutdownNow();
    return "success";
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43944305/article/details/113849672
今日推荐