scheduleAtFixedRate和scheduleWithFixedDelay区别

Java中的定时任务ScheduledExecutorService  Executors.newScheduledThreadPool

1.  scheduleAtFixedRate

表示以固定频率执行的任务,如果当前任务耗时较多,超过定时周期period,则当前任务结束后会立即执行。

2. scheduleWithFixedDelay

表示以固定延时执行任务,延时是相对当前任务结束为起点计算开始时间。

3. 实验测试代码:

     //定时Executors,重新自定义ThreadFactory,这样便于通过线程名称来识别
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1,
            new ThreadFactory() {
                int index = 0;
                public Thread newThread(Runnable r) {
                    index++;
                    return new Thread(r,""+index);
                }
            });
        /**
         * FixedRate表示会周期性的执行,如果执行时间长超过period的话,下一个周期会立即执行
         */
        //scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        //    public void run() {
        //        System.out.println("exectue start time =" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        //        System.out.println("scheule at fixed run...,threadName=" + Thread.currentThread().getName());
        //        try {
        //            Thread.sleep(10 * 1000);
        //        }catch (Exception e){
        //
        //        }
        //        System.out.println("finish time=" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        //    }
        //},0,5,TimeUnit.SECONDS);
        /**
         *  fixedDelay的话,是在上一次执行完再delay时间后执行
         */
        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                System.out.println("exectue start time =" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                System.out.println("scheule at fixed run...,threadName=" + Thread.currentThread().getName());
                try {
                    Thread.sleep(10 * 1000);
                }catch (Exception e){

                }
                System.out.println("finish time=" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            }
        },0,5,TimeUnit.SECONDS);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值