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

 Posted On  | Yashwant Chavan 

Recently One of my friend working on Email Downloader functionality. His requirement is pretty much simple. He have one common mail box as ( 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 (

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.


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 {
            } 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.


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);


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....

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0437 seconds.