Schedule a task Or Job to execute after Each 5 seconds Using Java

 Posted On  | Yashwant Chavan | Views :- 1422

Recently One of my friend working on Email Downloader functionality. His requirement is pretty much simple. He have one common mail box as (XXXX@gmail.com) and on that email id, it receives thousand of emails on daily basis along with XML file as a attachment. So application needs to read those emails after specified time interval and download the Xml attachment and update the database accordingly base on business logic. So below code is base on the above requirement.

Schedule Program Using Java (EmailDownloader.java)

"java.util.Timer" A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period. Here we specified delay as 5 seconds.

This is continuous running service, so I have used endless while loop, You can add exit logic as per your requirement.

package com.technicalkeeda.demo;

import java.util.Timer;

public class EmailDownloader {
	public static void main(String[] args) {
		Timer timer = new Timer();
		timer.schedule(new Downloader(), 0, 5000);

		while (true) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				System.out.println("InterruptedException Exception" 
                                + e.getMessage());
			}
		}
	}
}

Downloader .java

Create a TimerTask and override the abstract method public void run(). This run() method contains your business logic to download the emails.

package com.technicalkeeda.demo;

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

public class Downloader extends TimerTask{
	Date downloadTime ;
	public void run() {
		downloadTime = new Date();
		System.out.println("Email Downloaded...." + downloadTime);
	}
}

Output:-

Email Downloaded....Tue Apr 30 20:22:49 IST 2013
Email Downloaded....Tue Apr 30 20:22:54 IST 2013
Email Downloaded....Tue Apr 30 20:22:59 IST 2013
Email Downloaded....Tue Apr 30 20:23:04 IST 2013
Email Downloaded....Tue Apr 30 20:23:09 IST 2013
...
...
...
So on....

Tags Java  Timer 

HTML Comment Box is loading comments...

Hi I am Yashwant Chavan founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.

Latest Updates

Stay updated with latest post, articles and technical discussions.

Most Popular Articles



© technicalkeeda.com 2014