0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

scheduleAtFixedRate, schedulewithFixedDelay

Last updated at Posted at 2023-01-16

kickするのを定期的にinterval
scheduleWithFixedDelay 前の処理が終わってから定期的にinterval

below is scheduleWithFixedDelay sample

public class Outer {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
        s.scheduleWithFixedDelay(() -> {
            int interval = new Random().nextInt(10);
            try {
                System.out.print(interval);
                Thread.sleep(interval * 100);
            } catch (InterruptedException ex) {
                Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("end");
        },1,1,TimeUnit.SECONDS);
        int count = 1;
        while(true) {
            Thread.sleep(100);
            //if(s.isShutdown()) break;
            count++;
           System.out.print(">");
           if(count>100) {
               s.shutdown();
               break;
           }
        }
    }
}

1秒待機 initial delay
0.4秒処理
1秒待機 delay
0.4秒処理
1秒待機 delay
0.8秒処理
1秒待機 delay

>>>>>>>>>4>>>end
>>>>>>>>>>0end
>>>>>>>>>4>>>>end
>>>>>>>>>8>>>>>>>end
>>>>>>>>>6>>>>>>end
>>>>>>>>>1>end
>>>>>>>>>6>>>>>>end
>>>>>>>>>

scheduleAtFixedRateは、前の処理が時間かかりすぎるとintervalを使い果たしているので、次の処理がすぐ始まる
1秒待機 initial delay

0.5秒処理(period 1s)
0.5秒待機

0.7秒処理(period 1s)
0.3秒待機

>>>>>>>>>5>>>>end
>>>>>7>>>>>>end
>>>1>end
>>>>>>>>9>>>>>>>>end
>8>>>>>>>end
>>1>end
>>>>>>>>8>>>>>>>end
>>7>>>>>>>end
>>9>>>>>>>>>end
0end
>>>>>>>>>>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?