0
0

More than 1 year has passed since last update.

scheduledexecutorservice interface

Last updated at Posted at 2023-01-16

1秒後に実行
executorService#shutdown()することで
繰り返し処理が止まる

public class Outer {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
        s.schedule(() -> {
           System.out.println("xxx");
           s.shutdown();
        },1,TimeUnit.SECONDS);
        int count = 1;
        while(true) {
            Thread.sleep(100);
            if(s.isShutdown()) break;
           System.out.println((count++)*100);
        }
    }
}
100
200
300
400
500
600
700
800
900
xxx

1秒後に実行、その後定期2秒実行

public class Outer {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
        s.scheduleAtFixedRate(() -> {
           System.out.println("xxx");
//           s.shutdown();
        },1,2,TimeUnit.SECONDS);
        int count = 1;
        while(true) {
            Thread.sleep(100);
            //if(s.isShutdown()) break;
           System.out.println((count++)*100);
           if(count>100) {
               s.shutdown();
               break;
           }
        }
    }
}
100
200
300
400
500
600
700
800
900
xxx
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
xxx
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
4000
4100
4200
4300
4400
4500
xxx
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
xxx
6400
6500
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7600
7700
7800
7900
8000
8100
8200
xxx
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
0
0
1

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