Timer class in java gives capability to schedule tasks for future execution in a background thread.
Task can be schedule for one time execution or for multiple times after specified regular intervals.
Example
We will use Timer class to maintain a count of tasks processed in last one minute, five minute and ten minutes. We will also use AtomicInteger
Task can be schedule for one time execution or for multiple times after specified regular intervals.
Example
We will use Timer class to maintain a count of tasks processed in last one minute, five minute and ten minutes. We will also use AtomicInteger
import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; public class TimerTest extends Timer { private final AtomicInteger oneMinuteCounter; private final AtomicInteger fiveMinuteCounter; private final AtomicInteger tenMinuteCounter; public static final long MILLIS_IN_MINUTE = 60000; private Timer taskManager = new Timer("taskManager"); public TimerTest() { oneMinuteCounter = new AtomicInteger(0); fiveMinuteCounter = new AtomicInteger(0); tenMinuteCounter = new AtomicInteger(0); } protected static class Decrement extends TimerTask { private final AtomicInteger atomicInteger; public Decrement(AtomicInteger integer) { atomicInteger = integer; } @Override public void run() { atomicInteger.decrementAndGet(); } } public void executeTask() { oneMinuteCounter.incrementAndGet(); taskManager.schedule(new Decrement(oneMinuteCounter), MILLIS_IN_MINUTE); fiveMinuteCounter.incrementAndGet(); taskManager.schedule(new Decrement(fiveMinuteCounter), 5 * MILLIS_IN_MINUTE); tenMinuteCounter.incrementAndGet(); taskManager.schedule(new Decrement(tenMinuteCounter), 5 * MILLIS_IN_MINUTE); } public void printTaskExecution() { System.out.println(oneMinuteCounter.get()); System.out.println(fiveMinuteCounter.get()); System.out.println(oneMinuteCounter.get()); } public static void main(String... args) { TimerTest timer = new TimerTest(); for(int i=0; i <1000 ; i++) try { timer.executeTask(); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
No comments:
Post a Comment