Monday, March 7, 2016

How to run a task Concurrently using Timer Class

How to run a task concurrently?

package com.javaetutorials;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/* Scheduler Task :
 * How to run a task periodically in Java
To execute a method between a regular interval of time.*/

class ScheduledTask extends TimerTask {

     Date now; // to display current time
     // Add your task here
     public void run() {
          now = new Date(); // initialize date
          System.out.println("Time is :" + now);
     }
}

// Run Scheduled task
public class TimerApp {
     public static void main(String[] args) {
          Timer timer=new Timer();
          ScheduledTask sTask= new ScheduledTask();
          timer.schedule(sTask, 0, 2000);
     }
}

Output :

Time is :Tue Mar 08 00:11:15 IST 2016
Time is :Tue Mar 08 00:11:17 IST 2016
Time is :Tue Mar 08 00:11:19 IST 2016
Time is :Tue Mar 08 00:11:21 IST 2016

It keeps running until it comes with a terminate condition like System.exit(0)

Snippet of Timer class:

public class Timer {
     private final TaskQueue queue;
     private final TimerThread thread;
     private final Object threadReaper;
     private static final AtomicInteger nextSerialNumber = new AtomicInteger(0);


Snippet of TimerTask :

abstract class TimerTask implements Runnable {
     final Object lock = new Object();
     int state = 0;
     static final int VIRGIN = 0;
     static final int SCHEDULED = 1;
     static final int EXECUTED = 2;
     static final int CANCELLED = 3;

No comments:

Post a Comment