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";
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值