If you need to perform some task after a certain amount of time delay, or if you need to run it periodically at regular time intervals, you might want to consider a ScheduledThreadPoolExecutor.
ScheduledThreadPoolExecutor provides the following 4 methods.
- schedule(Runnable command, long delay, TimeUnit unit) : Execute the task once after a certain amount of time
- schedule(Callable
command, long delay, TimeUnit unit) : Executes the task once after a certain period of time and returns the result - scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) : Executes the task repeatedly at regular time intervals.
- scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit) : When the task is completed, it is executed again after a certain period of time. The difference from scheduleAtFixedRate() is that the end of the task is the standard.
schedule(Runnable)
schedule() is a method that executes a Job after a certain time (delay).
The arguments passed to schedule() are as follows.
- Runnable: Receives a Runnable with no return value as an argument
- delay : the amount of time to delay
- TimeUnit : The unit of time
package concurrent;
import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolExecutorExample1 {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Runnable runnable = () -> System.out.println("Runnable task : " + LocalTime.now());
int delay = 3;
// schedule the job
System.out.println("Scheduled task : " + LocalTime.now() );
executor.schedule(runnable, delay, TimeUnit.SECONDS);
}
}
result
Scheduled task : 22:58:43.006
Runnable task : 22:58:46.007
schedule(Callable)
schedule() is a method that executes a Job after a certain period of time.
The arguments passed to schedule() are as follows.
- Callable
: Callable returning T receive as a character - delay : the amount of time to delay
- TimeUnit : The unit of time
schedule() is called ScheduledFuture
package concurrent;
import java.time.LocalTime;
import java.util.concurrent.*;
public class ScheduledThreadPoolExecutorExample2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Callable<String> callable = () -> "Callable task : " + LocalTime.now();
int delay = 3;
// schedule the job
System.out.println("Scheduled task : " + LocalTime.now() );
ScheduledFuture<String> future =
executor.schedule(callable, delay, TimeUnit.SECONDS);
// Wait for results to be returned
String result = future.get();
System.out.println(result);
}
}
result
Scheduled task : 23:00:00.025
Callable task : 23:00:03.027
scheduleAtFixedRate()
scheduleAtFixedRate() is a method that runs a task at regular time intervals.
The arguments passed to scheduleAtFixedRate() are as follows.
- Runnable: Receives a Runnable with no return value as an argument
- initialDelay : The time to wait when the job is first executed
- delay : the time interval for the job to run
- TimeUnit : The unit of time
If you look at the result of the following example, you can see that after the job is executed (regardless of the completion time), the job is executed again after a certain delay.
package concurrent;
import java.time.LocalTime;
import java.util.concurrent.*;
public class ScheduledThreadPoolExecutorExample3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Runnable runnable = () -> {
System.out.println("++ Repeat task : " + LocalTime.now());
sleepSec(3);
System.out.println("-- Repeat task : " + LocalTime.now());
};
int initialDelay = 2;
int delay = 3;
// schedule the job
System.out.println("Scheduled task : " + LocalTime.now() );
executor.scheduleAtFixedRate(
runnable, initialDelay, delay, TimeUnit.SECONDS);
}
private static void sleepSec(int sec) {
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
result
Scheduled task : 23:01:48.967
++ Repeat task : 23:01:50.969
-- Repeat task : 23:01:53.969
++ Repeat task : 23:01:53.970
-- Repeat task : 23:01:56.970
++ Repeat task : 23:01:56.971
-- Repeat task : 23:01:59.971
++ Repeat task : 23:01:59.971
-- Repeat task : 23:02:02.972
++ Repeat task : 23:02:02.972
-- Repeat task : 23:02:05.972
++ Repeat task : 23:02:05.973
-- Repeat task : 23:02:08.973
....
scheduleWithFixedDelay()
scheduleAtFixedRate() is a method that executes the job again after a certain period of time after the job is completed.
The arguments passed to scheduleWithFixedDelay() are as follows.
- Runnable: Receives a Runnable with no return value as an argument
- initialDelay : The time to wait when the job is first executed
- delay : The amount of time to wait until the next job is executed after a job is completed
- TimeUnit : The unit of time
If you look at the result of the following example, you can see that the next job is executed after waiting for delay after the job is finished.
package concurrent;
import java.time.LocalTime;
import java.util.concurrent.*;
public class ScheduledThreadPoolExecutorExample4 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Runnable runnable = () -> {
System.out.println("++ Repeat task : " + LocalTime.now());
sleepSec(3);
System.out.println("-- Repeat task : " + LocalTime.now());
};
int initialDelay = 2;
int delay = 3;
// schedule the job
System.out.println("Scheduled task : " + LocalTime.now() );
executor.scheduleWithFixedDelay(
runnable, initialDelay , delay, TimeUnit.SECONDS);
}
private static void sleepSec(int sec) {
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
result
Scheduled task : 23:03:29.282
++ Repeat task : 23:03:31.284
-- Repeat task : 23:03:34.285
++ Repeat task : 23:03:37.285
-- Repeat task : 23:03:40.286
++ Repeat task : 23:03:43.286
-- Repeat task : 23:03:46.286
++ Repeat task : 23:03:49.287
-- Repeat task : 23:03:52.287
++ Repeat task : 23:03:55.288
-- Repeat task : 23:03:58.288
++ Repeat task : 23:04:01.288
-- Repeat task : 23:04:04.289
....
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)