Cron Job (Job scheduler) for Web Application

This Cron job(Timer Task, Job scheduler) Start when web application deploying and run according to give time schedule. For adjust the time want to edit time rage of class.

1. Add following 2 java class in to web application and adjust time with request time period.
2. Add Listener class property in to web.xml


Web XML entry





Listener class


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.itfac.chandana;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
*
* @author Chandana
*/
public class WisdomListener implements ServletContextListener {

private ServletContext context = null;

public void contextDestroyed(ServletContextEvent event) {

System.out.println("Application is undeploying");
this.context = null;

}

public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
TimerTaskScheduler taskShe = new TimerTaskScheduler();
taskShe.test();
System.out.println("Application is deploying");

}
}

TimerTaskScheduler

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.itfac.chandana;

import java.util.Calendar;
import java.util.Timer;

/**
*
* @author Chandana
*/
public class TimerTaskScheduler {

public void test() {
Timer timer = new Timer();
Calendar date = Calendar.getInstance();
date.set(Calendar.HOUR, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 2);
date.set(Calendar.MILLISECOND, 0);
// Schedule to run every Sunday in midnight
timer.schedule(new JobRunner(), date.getTime(), 1000*60*60*24);
}

}


JobRunner

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.itfac.chandana;


import java.util.Calendar;
import java.util.Date;
import java.text.*;
import java.sql.*;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Chandana
*/
class JobRunner extends TimerTask {

public JobRunner() {
}

@Override
public void run() {
System.out.println("Generating ");
/**
*Your Cron jobs code want to pply here.

}

}

Comments

Anonymous said…
Awesome work. Loved the way in simple terms you have explained such a big thing.

I am starter in JAVA and understood perfectly.

Popular posts from this blog

XSLT - Modify Date and DateTime value

Integrate With Mutual Certificate Authentication based Service

Yield Price Sri Lanka - Android Application