Run some task periodically using core java concepts

In this example we are going to write a java program which will run every 2 seconds and will perform some task for us. In our example we are simply going to print the new date time stamp after every two seconds but in a real world there could be plenty of scenarios one can think of. One example could be updating the user interface after every few seconds and fetch the latest data from the database.

The code is pretty self explanatory, by looking at the embedded comments it will be even easier. 

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Amzi
 */
public class Scheduler extends TimerTask {

    Date currentTime;

    // Add your core logic/business use case
    public void run() {
        currentTime = new Date();
        System.out.println("The current Time is :" + currentTime);
    }

    public static void main(String args[]) throws InterruptedException {

        Timer timer = new Timer(); // Step 1 - Instantiate Timer Object
        Scheduler sc = new Scheduler(); // Step 2 - Instantiate the class
        timer.schedule(sc, 0, 2000); // Step 3 - Create task for every 2 seconds
        // Using the for loop along with the System.exit to terminate the
        // program otherwise it will keep on running
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread..." + i);
            // Make thread sleep for 2 seconds
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("We are getting out of here...");
                System.exit(0);
            }
        }
    }
}


The above code will print the following output into the console.

Execution in Main Thread...0
The current Time is :Mon Nov 25 14:33:07 EST 2013
Execution in Main Thread...1
The current Time is :Mon Nov 25 14:33:09 EST 2013
Execution in Main Thread...2
The current Time is :Mon Nov 25 14:33:11 EST 2013
Execution in Main Thread...3
The current Time is :Mon Nov 25 14:33:13 EST 2013
Execution in Main Thread...4
The current Time is :Mon Nov 25 14:33:15 EST 2013
The current Time is :Mon Nov 25 14:33:17 EST 2013
Execution in Main Thread...5
We are getting out of here...
The current Time is :Mon Nov 25 14:33:19 EST 2013




No comments:

Post a Comment