java scheduleAtFixedRate example. How to schedule a task to execute at a fixed time every day.

In this tutorial, let us see how to schedule a task to execute at a fixed time every day. For example, you may want to send SMS to your clients every day at 7PM. In java, this can be done in many ways. One way to do this is to use Timer class and scheduleAtFixedRate method.

Timer Class : used to schedule tasks (a class that extends TimerTask class) for one time or for repeated times at regular intervals using various methods such as scheduleAtFixedRate.

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

-> the above method accepts the task to be executed and enables it to execute after given initial delay and and subsequently with the given period.

Let us see an example with Timer Class and scheduleAtFixedRate. The following code helps to execute the given task each day at 7PM.

package com.javaonline;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class ScheduleJobExample {

	public static void main(String args[])
	{
	 	Calendar date = Calendar.getInstance();

		SMSTimer smsTimer=new SMSTimer();

		date.set(Calendar.HOUR, 7);
		date.set(Calendar.MINUTE,0 );
 	        date.set(Calendar.SECOND, 0);
		date.set(Calendar.MILLISECOND, 0);
		smsTimer.scheduleSMSSend(date, 24);
 }

}

class SMSTimer
{
	Timer timer=new Timer();

	public void scheduleSMSSend(Calendar date, int period) {
	    System.out.println("Inside SMS Send Execute");
	     timer.scheduleAtFixedRate(	new SmsSendTask(), date.getTime(), 1000 * 60 * 60 * period   ); //Executes the below task each day at 7PM

	   }
}   

class SmsSendTask extends TimerTask {
			          public void run() {
			         	  System.out.println("Called at 7PM ");

				     //code to send SMS.

				  }

} 

Running the above program, will execute run method of the class SmsSendTask is executed at 7PM

Output :

java sheduleatfixedrate

Reference : Timer Class

Leave a Reply