Java Timer

 

Timer and TimerTask classes are important java util class used to schedule tasks in a background thread. On other way TimerTask is a task performer and Timer is a scheduler to set the time to run the task. By using these classes we can schedule the task to run at a specified time once or we can set repeated task at an interval. Lets see simple Java example for both by scheduling task once and repeated task at an interval.
Java Timer


Scheduling Task Once:


import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class JavaTimer {

 public static void main(String[] args) {
  
  TimerTask task = new TimerTask() {
         public void run() {
             Random rand = new Random();
             System.out.println(Thread.currentThread().getName() + rand.nextInt(1000));
         }
     };
     
     Timer timer = new Timer("Generate Random Number : ");
      
     long delay = 500L;
     timer.schedule(task, delay);
 }
}


OUTPUT:


Generate Random Number : 237





Repeated Task at Interval:


import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class JavaTimer {

 public static void main(String[] args) {
  
  TimerTask task = new TimerTask() {
         public void run() {
             Random rand = new Random();
             System.out.println(Thread.currentThread().getName() + rand.nextInt(1000));
         }
     };
     
     Timer timer = new Timer("Generate Random Number : ");
      
     long delay = 500L;
     long period = 1000L;
     timer.scheduleAtFixedRate(task, delay, period);;
 }
}


OUTPUT:


Generate Random Number : 519
Generate Random Number : 973
Generate Random Number : 859
Generate Random Number : 942
Generate Random Number : 578
Generate Random Number : 764
Generate Random Number : 256
Generate Random Number : 802
Generate Random Number : 926
Generate Random Number : 69
Generate Random Number : 875
.
.
.

1 comment:
Write comments