How to implement alarm clock functionality to alarm sound at 7 am on week days and 10 am on weekends using java schedular
Steps to schedule a alarm clock during the week days or week ends
Step1. Write an abstract class wich implements Runnable and has the method to implement the logic to alarm sound.
package com.vels.test;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public abstract class SchedulerTask implements Runnable {
final Object lock = new Object();
int state = VIRGIN;
static final int VIRGIN = 0;
static final int SCHEDULED = 1;
static final int CANCELLED = 2;
TimerTask timerTask;
protected SchedulerTask() {
}
public abstract void run();
public boolean cancel() {
synchronized(lock) {
if (timerTask != null) {
timerTask.cancel();
}
boolean result = (state == SCHEDULED);
state = CANCELLED;
return result;
}
}
public long scheduledExecutionTime() {
synchronized(lock) {
return timerTask == null ? 0 : timerTask.scheduledExecutionTime();
}
}
}
Stpe 2 : Write a schedular to schedule tha alarm clock to sound
package com.vels.test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class Scheduler {
class SchedulerTimerTask extends TimerTask {
private SchedulerTask schedulerTask;
private ScheduleIterator iterator;
public SchedulerTimerTask(SchedulerTask schedulerTask,
ScheduleIterator iterator) {
this.schedulerTask = schedulerTask;
this.iterator = iterator;
}
public void run() {
schedulerTask.run();
reschedule(schedulerTask, iterator);
}
}
private final Timer timer = new Timer();
public Scheduler() {
}
public void cancel() {
timer.cancel();
}
public void schedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {
Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.VIRGIN) {
throw new IllegalStateException("Task already scheduled " + "or cancelled");
}
schedulerTask.state = SchedulerTask.SCHEDULED;
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}
private void reschedule(SchedulerTask schedulerTask,
ScheduleIterator iterator) {
Date time = iterator.next();
if (time == null) {
schedulerTask.cancel();
} else {
synchronized(schedulerTask.lock) {
if (schedulerTask.state != SchedulerTask.CANCELLED) {
schedulerTask.timerTask =
new SchedulerTimerTask(schedulerTask, iterator);
timer.schedule(schedulerTask.timerTask, time);
}
}
}
}
}
Step 3 : Write an Schedule iterator
package com.vels.test;
import java.util.Date;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public interface ScheduleIterator {
public Date next();
}
Step 4 : Write a Restricted Daily Iterator - it is restricted to run a job on particular days of the week;
package com.vels.test;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class RestrictedDailyIterator implements ScheduleIterator {
private final int hourOfDay;
private final int minute;
private final int second;
private final int[] days;
private final Calendar calendar = Calendar.getInstance();
public RestrictedDailyIterator(int hourOfDay, int minute, int second, int day) {
this(hourOfDay, minute, second, new int[]{day});
}
public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days) {
this(hourOfDay, minute, second, days, new Date());
}
public RestrictedDailyIterator(int hourOfDay, int minute, int second, int[] days, Date date) {
this.hourOfDay = hourOfDay;
this.minute = minute;
this.second = second;
this.days = (int[]) days.clone();
Arrays.sort(this.days);
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, 0);
if (!calendar.getTime().before(date)) {
calendar.add(Calendar.DATE, -1);
}
}
public Date next() {
do {
calendar.add(Calendar.DATE, 1);
} while (Arrays.binarySearch(days, calendar.get(Calendar.DAY_OF_WEEK)) < 0);
return calendar.getTime();
}
}
Step 5 : Write Composit iterator class - takes a set of ScheduleIterators and correctly orders the dates into a single schedule.
package com.vels.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Date;
/**
* @author velmurugan pousel
* @project EmailScheduler
* created on Feb 2, 2011
*/
public class CompositeIterator implements ScheduleIterator {
private List orderedTimes = new ArrayList();
private List orderedIterators = new ArrayList();
public CompositeIterator(ScheduleIterator[] scheduleIterators) {
for (int i = 0; i < scheduleIterators.length; i++) {
insert(scheduleIterators[i]);
}
}
private void insert(ScheduleIterator scheduleIterator) {
Date time = scheduleIterator.next();
if (time == null) {
return;
}
int index = Collections.binarySearch(orderedTimes, time);
if (index < 0) {
index = -index - 1;
}
orderedTimes.add(index, time);
orderedIterators.add(index, scheduleIterator);
}
public synchronized Date next() {
Date next = null;
while (!orderedTimes.isEmpty() && (next == null || next.equals((Date) orderedTimes.get(0)))) {
next = (Date) orderedTimes.remove(0);
insert((ScheduleIterator) orderedIterators.remove(0));
}
return next;
}
}
Step 6 : Write an alarm clock class - it will alarm sound at 7am on week days and 9 am on weekend
package com.vels.test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class AlarmClock {
private final Scheduler scheduler = new Scheduler();
private final SimpleDateFormat dateFormat =
new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS");
public AlarmClock() {
}
public void start(ScheduleIterator iterator) {
scheduler.schedule(new SchedulerTask() {
public void run() {
soundAlarm();
}
private void soundAlarm() {
System.out.println("Wake up! " +
"It's " + dateFormat.format(new Date()));
// Start a new thread to sound an alarm...
}
}, iterator);
}
public static void main(String[] args) {
int[] weekdays = new int[] {
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY
};
int[] weekend = new int[] {
Calendar.SATURDAY,
Calendar.SUNDAY
};
ScheduleIterator i = new CompositeIterator(
new ScheduleIterator[] {
new RestrictedDailyIterator(7, 0, 0, weekdays),
new RestrictedDailyIterator(9, 0, 0, weekend)
}
);
AlarmClock alarmClock = new AlarmClock();
alarmClock.start(i);
}
}
......
Wake up! It's 02 Feb 2011 12:28:00.011
.....
Reference : http://www.ibm.com/...
Showing posts with label Scheduler. Show all posts
Showing posts with label Scheduler. Show all posts
Wednesday, February 2, 2011
Tuesday, February 1, 2011
Job Scheduling in Java
How to Schedule a Job or Task in Java
To schedule a job to occur at a certain time or to be excuted at repeated time interval
we can use TimerTask and Timer class in java to accomplish this.
A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.”
A TimerTask is similar to a Thread. Both classes implement the Runable interface.
Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread
A Timer is facility to schedule TimerTasks.
"Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
Timer tasks should complete quickly."
The constructor of the Timer class starts the background thread.
package com.vels.test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class EmailTask extends TimerTask {
/**
* method will be called at every scheduled time(ex ..1 minute)
*/
public void run() {
System.out.println(" start to send mail...." + new Date());
sendMail();
System.out.println(" after mail sent...." +
System.currentTimeMillis());
}
public void sendMail() {
System.out.println(" email send.....");
}
public static void main(String[] args) {
int DELAY = 60*1000; // one minute delay
Timer t1 = new Timer();
t1.schedule(new EmailTask(),DELAY, DELAY);
//calls the run method to send mail after one minute and
repeat every one minute.
// task - task to be scheduled.
// delay - delay in milliseconds before task is to be
executed.
// period - time in milliseconds between successive task
executions.
}
}
To cancel the Scheduled task we need to call cancel method of the TimerTask( we can override the cancel method).
To schedule a job to occur at a certain time or to be excuted at repeated time interval
we can use TimerTask and Timer class in java to accomplish this.
A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.”
A TimerTask is similar to a Thread. Both classes implement the Runable interface.
Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread
A Timer is facility to schedule TimerTasks.
"Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.
Timer tasks should complete quickly."
The constructor of the Timer class starts the background thread.
package com.vels.test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class EmailTask extends TimerTask {
/**
* method will be called at every scheduled time(ex ..1 minute)
*/
public void run() {
System.out.println(" start to send mail...." + new Date());
sendMail();
System.out.println(" after mail sent...." +
System.currentTimeMillis());
}
public void sendMail() {
System.out.println(" email send.....");
}
public static void main(String[] args) {
int DELAY = 60*1000; // one minute delay
Timer t1 = new Timer();
t1.schedule(new EmailTask(),DELAY, DELAY);
//calls the run method to send mail after one minute and
repeat every one minute.
// task - task to be scheduled.
// delay - delay in milliseconds before task is to be
executed.
// period - time in milliseconds between successive task
executions.
}
}
To cancel the Scheduled task we need to call cancel method of the TimerTask( we can override the cancel method).
Subscribe to:
Posts (Atom)