ScheduledExecutorService

The Interface...


The ScheduledExcecutorService is an interface. That means it dictates what methods the service must have but doesn't do anything else... cause in java... that's what interfaces do... boss classes around... it's the java way.

So we need a class that implements the interface... and there just happens to be one in the java.util.concurrent package. We can create it using the Executor utility class that has a factory method to create the scheduler. That factory method is newScheduledThreadPool(int) the parameter (an int) --> how many threads you want to start.

The threads themselves are autonomous... i.e. they run in their own space. That means you need to shut them down or it will keep the JVM alive. Use the shutdown() method to accomplish this task.

CREATED 2020-09-27 11:55:06.0

010-00-03-33

UPDATED 2020-09-27 12:16:12.0

Example


package com.leistware.timer.TimerTest; import com.leistware.TimeStamp; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import static java.util.concurrent.TimeUnit.*; class TheTimeTimer {    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);    private int count = 0;    public void printTime() {    final Runnable printIt = () -> {       String time = new TimeStamp().serializeTime();       System.out.print(" " + time);    };    final ScheduledFuture

















< > timeHandle =       scheduler.scheduleAtFixedRate(printIt, 1, 1, SECONDS);    scheduler.schedule(() -> {          timeHandle.cancel(true);          scheduler.shutdown();       }, 10, SECONDS);    }    public static void main(String[] args){       TheTimeTimer t = new TheTimeTimer();       t.printTime();    } }










CREATED 2020-09-27 11:12:05.0

010-00-03-32

UPDATED 2020-09-27 11:55:09.0

L
I
N
K
S

DBID: db.wam

Page Server: Ithica

©2019 Leistware.com
        Hello anonymous