Home Java Task Scheduling in JAVA
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Task Scheduling in JAVA

Advertisement
In some applications some task need to run periodically, for example a application of report generating checks for new database entry after one day and make reports according to the entries then save all entries in company's permanent record.

Task Scheduling in JAVA

     

In some applications some task need to run periodically, for example a application of report generating checks for new database entry after one day and make reports according to the entries then save all entries in company's permanent record.

Java provide facility to schedule tasks as per requirement. This is example given below to schedule a simple task to display a message after 3 seconds.

Methods and classes used in this example :

java.util.TimerTask class specifies a task that can be scheduled to run once or after scheduled time. We can define action to be performed by this timer task. by using run() method of java.util.TimeTask. This is protected method.

java.util.Timer class provides facility to schedule tasks for future execution in a background thread. In this example we have used schedule() method of this class that specifies task for execution after the specified delay. It takes time delay as a parameter in milliseconds.

Note : Use ctrl + C to exit from this program.

TaskScheduling.java

import java.util.*;
class Task extends TimerTask {
  
    int count = 1;
      // run is a abstract method that defines task performed at scheduled time.
    public void run() {
        System.out.println(count+" : Mahendra Singh");
	    count++;
    }
}
class TaskScheduling {
   public static void main(String[] args) {
       Timer timer = new Timer();
   
       // Schedule to run after every 3 second(3000 millisecond)
       timer.schedule( new Task(), 3000);	
   }
}


Output of the program :

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 29, 2008

Ask Questions?    Discuss: Task Scheduling in JAVA   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
TQ
October 21, 2011
bug

I got the above code to work with the slight change of timer.schedule( new Task(), 0, 1000); where 0 is the initial delay.
Vijay
January 28, 2013
Incorrect output

The above program gives incorrect output which is not same as show above.
3configurators
June 25, 2012
error

this code doesn't work
vishal Anekar
September 11, 2013
learn java language

guidance about implementation of k-map using graphics in java
DMCA.com