Posts tagged ‘spring’

Spring – Quartz scheduler setup

The Spring Application Framework ships with helper classes to make configuring OpenSymphony’s quartz scheduler a breeze. The scheduler allows (amongst other things) cron style triggers. At the time of writing, the latest version of Quartz is 1.6.3, but I’ll be using 1.6.0 as this is the latest version in the Maven central repos.

First, download the version you wish to use and add as a dependency to your project. In Maven‘s case, add this to the pom.xml:

<dependency>
  <groupId>opensymphony</groupId>
  <artifactId>quartz</artifactId>
  <version>1.6.0</version>
</dependency>

Now, create your task which extends org.springframework.scheduling.quartz.QuartzJobBean and implement public void executeInternal(JobExecutionContext context) throws JobExecutionException. You can inject any necessary beans too (myService in this example).

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class myTask extends QuartzJobBean {
  private MyService myService;

  public void setMyService(MyService myService) {
    this.myService = myService;
  }

  public void executeInternal(JobExecutionContext context) throws JobExecutionException {
    Actual Business Logic
  }
}

Create a schedulingContext-timer.xml to keep the scheudling configuration seperate and place in the WEB-INF folder of your Spring webapp. These settings could also go in the applicationContext.xml if you prefer but I like to keep the configuration seperate.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <!-- Job details -->
  <bean id="myTask" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="com.mycompany.project.scheduling.MyTask"/>
    <property name="jobDataAsMap">
      <map>
        <entry key="myService" value-ref="myServiceBean"/>
      </map>
    </property>
  </bean>

   <!-- Cron -->
  <bean id="myTaskCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="myTask"/>
    <property name="cronExpression" value="0 0/5 * * * ?"/>
  </bean>

   <!-- Kicker -->
  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
      <list>
        <ref bean="myTaskCronTrigger"/>
      </list>
    </property>
  </bean>
</beans>

A couple of notes:

  • “Job details” is where you inject any required beans
  • This example uses a CronTriggerBean as this provides functionality otherwise not present in a simple Timer. In the example, the trigger is set to run every 5 minutes starting on the hour. For a full list of possible cron settings, click here.
  • Available triggers are CronTrigger, SimpleTrigger and UICronTrigger. See here.
  • The “Kicker” is required to actually make use of the triggers you’ve set up
  • If you’ve used a separate context, remember to add its name to the web.xml under contextConfigLocation

And that’s all… your webapp now has full Cron capabilities! Enjoy 🙂

November 25, 2008 at 5:55 pm Leave a comment

ehcache and spring

As used by Hibernate, ehcache is a great little caching implementation which ought to be part of every Java coders arsenal. Although its complexities may seem overwhelming, it’s very easy to use as a simple caching solution.

In my situation, I needed to prevent db hits when validating codes (ie seeing if they already exist in the db). This is how easy it is to set up.

applicationContext.xml:

<bean id="myDao" class="myDaoImpl" init-method="setupCache">
  <property name="cacheManager" ref="cacheManager">
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="classpath:ehcache.xml" />
</bean>

ehcache.xml:

<ehcache>
  <diskStore path="java.io.tmpdir"/>
  <cache name="myCacheName"
    maxElementsInMemory="1000"
    eternal="true"
    overflowToDisk="false"/>
  <defaultCache
    maxElementsInMemory="300"
    maxElementsOnDisk="1000"
    eternal="false"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120"
    overflowToDisk="true"/>
</ehcache>

myDaoImpl.java:

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class {
  private CacheManager cacheManager;
  private Cache myCache = null;

  public void setCacheManager(CacheManager cacheManager) {
    this.cacheManager = cacheManager;
  }

  private void setupCache() {
    String cacheName = "myCacheName";
    logger.debug("Fetching cache [" + cacheName + "]");
    myCache = cacheManager.getCache(cacheName);
  }
}

ehcache.xml needs to be put alongside applicationContext.xml (especially in the case of jar packaging). If you’re packaging a war, you can place it anywhere on the classpath and don’t need to specify the configLocation (it’s the default config name).

To use the cache, do something like this:

Element cachedObject = myCache.get(key);
if (cachedObject != null) {
  return cachedObject;
} else {
  fetch object from db
  // add to cache
  myCache.put(new Element(key, object))
  return object;
}

And that's it!

Now you’ll only hit the db when needed. Of course, it’s worth reading the reference material to see the many ways you can configure the cache. My example is purely for a 1000 object permanent memory cache, but TTL and overflow-to-disk (for example) is just as easy to set up.

October 23, 2008 at 4:28 pm 4 comments