MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to schedule Recurring Tasks in Java Applications

We will discuss about scheduling tasks in java application. Java provides various APIs to implement recurring tasks and we will implement those in our discussion.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction:

In some Java applications we need to run certain programs at regular intervals. A common example of this is generating reports periodically. Java provides the feature to schedule such tasks as per the requirement.

Timer is an important component in java to schedule tasks/jobs for one time and also repeated execution. Timer utility is also used in mobile development and the functionality is similar to that of a java application. There is another utility known as Reminder in java and it is also used widely along with Timer class. So the two classes Timer and TimerTask are the main components in Timer API. Java application uses both of them to implement various functionalities. But we need to understand the functionality of Timer and TimerTask separately. The TimerTask is the actual task/job to be executed and the Timer is some kind of helper who actually executes it. TimerTask is also linked with java thread. It implements Runnable interface and overrides run method to perform specific tasks. So the two classes are at the heart of scheduled recurring task implementation in java.

Let us consider the following code snippet:

Listing 1: A sample timer example

package com.home.timer ;

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

public class MyTimer extends TimerTask {
	Timer timer ;
	int count = 0 ;
	public MyTimer () {
	}
	public MyTimer ( Timer timer ) {
		this.timer = timer ;
	}
	public void toDo() {
		System.out.println( " Count-> " + (count++) + " : Hello World ! This is java scheduler " );
	}
	@Override
	public void run () {
		toDo () ;
		if (count > 10) {// this is the condition when you want to stop the
							// task.
			timer.cancel () ;
		}
	}
}

package com.home.timer ;

import java.util.Timer ;

public class MyScheduler {
	public static void main( String [] args ) {
	     Timer timer = new Timer() ;
	     MyTimer myTask = new MyTimer ( timer ) ;
	     int firstSart = 1000 ; // it means after 1 second.
	     int period = 1000*2 ; //after which the task will repeat;
	     timer.schedule(myTask, firstSart, period) ;//the time specified in millisecond.     
	 }
}

In the above example as we see that the class MyTimer extends the java.util.TimerTask class which has an abstract method run. This run needs to be implemented in our class. In addition to this we have method toDo which actually does the task. In the run method we have a condition that if the count reaches 10 the program will execute for the last time and then stop. The java task scheduler can be used to schedule tasks of the following types:

  • One shot task
  • Recurring tasks

Features of Timer and TimerTask classes:

  • Timer task can use its cancel method to cancel all scheduled tasks
  • Timer can also be used to run as a daemon thread
  • Timer task can be scheduled to start at a fixed interval
  • It can be used to run in background for future execution
  • Tasks can be configured to run as a single or recurring execution
  • TimerTask is a thread handler and it is used to register tasks with timer

Scheduling One Shot task:

Let us consider the following code snippet:

Listing 2: One shot scheduler

package com.home.timer ;

import java.awt.Toolkit ;
import java.util.Timer ;
import java.util.TimerTask ;

public class RiceTimer {

	private final Timer timer = new Timer () ;
	private final int minutes ;

	public RiceTimer( int minutes ) {
		this.minutes = minutes ;
	}

	public void start() {
		timer.schedule(new TimerTask() {
			public void run () {
				playSound () ;
				timer.cancel () ;
			}

			private void playSound() {
				System.out.println ( " Your rice is ready! " );
				Toolkit.getDefaultToolkit().beep() ;
			}
		}, minutes * 60 * 1000);
	}

	public static void main( String[] args ) {
		RiceTimer riceTimer = new RiceTimer (20) ;
		riceTimer.start () ;
	}
}
 

In the code let us assume that it takes 20 minutes for a rice to get boiled. In the above program, the beep sound buzzes after 20 minutes with a message indicating that the rice is ready. This program runs one time and stops after its first execution. In one shot scheduler, the run method is invoked when the time is over. It plays the beep sound displays the message on the screen. The application terminates once the timer is executed.

Scheduling recurring tasks:

The java timer can be used to schedule tasks which keep on recurring at regular interval. E.g. the code snippet in Listing 1 prints the following:

Listing 3: Output of a recurring scheduler

Count-> 0 : Hello World ! This is java scheduler
Count-> 1 : Hello World ! This is java scheduler
Count-> 2 : Hello World ! This is java scheduler
Count-> 3 : Hello World ! This is java scheduler
Count-> 4 : Hello World ! This is java scheduler
Count-> 5 : Hello World ! This is java scheduler
Count-> 6 : Hello World ! This is java scheduler
Count-> 7 : Hello World ! This is java scheduler
Count-> 8 : Hello World ! This is java scheduler
Count-> 9 : Hello World ! This is java scheduler
Count-> 10 : Hello World ! This is java scheduler

As we see here that the scheduler stops when the count reaches 10. This check is mentioned in the code. If we have a requirement to run this program indefinitely we need to get rid of the check: if (count > 10).

Another example of a recurring task scheduler could be that of an alarm clock or generating a daily report every morning at 2 AM. The simple alarm clock implementation is listed below. In this implementation every morning at 6:00 AM there will be a beep sound with a message showing the date and time.

Listing 4: An alarm clock implementation

package com.home.timer ;

import java.awt.Toolkit ;
import java.text.SimpleDateFormat ;
import java.util.Date ;

import org.tiling.scheduling.Scheduler ;
import org.tiling.scheduling.SchedulerTask ;
import org.tiling.scheduling.examples.iterators.DailyIterator ;

public class AlarmClock {
	private final Scheduler scheduler = new Scheduler () ;
    private final SimpleDateFormat dateFormat =
        new SimpleDateFormat( " dd MMM yyyy HH:mm:ss.SSS " ) ;
    private final int hourOfDay, minute, second ;

    public AlarmClock( int hourOfDay, int minute, int second ) {
        this.hourOfDay = hourOfDay ;
        this.minute = minute ;
        this.second = second ;
    }

    public void start () {
        scheduler.schedule (new SchedulerTask () {
            public void run () {
                soundAlarm () ;
            }
            private void soundAlarm () {
                System.out.println("Hello Good Morning ! " +
                    "It's " + dateFormat.format ( new Date () ) ) ;
                Toolkit.getDefaultToolkit().beep() ;
            }
        }, new DailyAlarmIterator (hourOfDay, minute, second) ) ;
    }

    public static void main ( String [] args ) {
        AlarmClock alarmClock = new AlarmClock ( 6, 0, 0 );
        alarmClock.start () ;
    }
}

This program is different from the rice timer program as we see that here we create an instance of the Scheduler (org.tiling.scheduling.Scheduler) rather than that of the Timer (java.util.Timer) to play the alarm. Also instead of scheduling the task after a fixed delay as in listing 1, this program uses a DailyIterator class to define the schedule. The DailyIterator class implements the SheduleIterator interface. The ScheduleIterator defines the execution of a SchedulerTask as a series of java.util.Date objects. The next () method in the ScheduleIterator then iterates over the Date objects in a chronological order. The DailyAlarmIterator class' next method returns the Date objects which represents the same time every day 6:00 AM. So, on call of the next () method we get 6:00 AM of the subsequent days. This keeps on repeating till the program is stopped.

The Scheduling framework:

The Scheduling framework consists of three components:

  • The ScheduleIterator Interface.
  • The Scheduler class.
  • The SchedulerTask class.

Out of these three we already have talked about the SchedulerInterface in detail. The other two Scheduler class and SchedulerTask class are based on Timer and TimerTask classes respectively.

Similar to the rice timer, each and every instance of Scheduler creates an instance of Timer to provide the underlying scheduling. Instead of the single one-shot timer used to implement the rice timer, the Scheduler strings together a chain of one-shot timers to execute a SchedulerTask class which are specified by the ScheduleIterator.

Conclusion:

So far we have discussed about the scheduler and recurring tasks and their implementation. I hope you have got a good understanding about the concepts and implementation. Following are some points to remember before we choose the correct implementation.

  • In Java a developer can run a single program repeatedly at a certain interval. This is called task scheduling.
  • Scheduler can be used in the following situations :
    • Set up an alarm clock.
    • Get reports at a regular interval.
  • Scheduler can be of two types :
    • One shot scheduler.
    • Recurring scheduler.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login