Friday 25 April 2014

How to schedule a task in java

Here is an easy code to explain the TimerTask ...

Create a TimerTask by creating a class which will extend TimerTask..
The code is  given below

package com.nik.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    int time;

    public void myTask() {
        System.out.println("This task is invoked after " + time + " minute");
    }

    public MyTimerTask(int time) {
        this.time = time;
    }

    @Override
    public void run() {
        myTask();
    }

}


 Another class to invoke the timer

 package com.nik.timer;

import java.util.Timer;

public class TimerDemo {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Timer started........");
        Timer myTimer = new Timer();
        myTimer.schedule(new MyTimerTask(1), 6000);
        Thread.sleep(6000);
        myTimer.cancel();
    }

}