Grails: caching using cron jobs

21 / Aug / 2009 by Amit Jain 2 comments

Hi,

We needed to cache the result of a webservice. We were using grails 1.1.1 version and springcache plugin for caching. Unfortunately, current springcache version didn’t work with grails 1.1.1. So we decided to cache the results using cron jobs, which will run in the background after every 1hr and store the results in a list, which will have a application level scope.

To implement this functionality, we used quartz plugin (http://grails.org/Quartz+plugin). This made our job easier. Below I have given the code, which did caching for us :

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class FetchRecentBlogsJob {
      def utilService
      def concurrent = false
      def startDelay = 1000*10
      def timeout = 1000*60*60

      def execute() {
                CH.config.recentBlogs = utilService.getRecentExcerptedPosts(2)
       }
}

This excute method in the above class runs after every one hour, which gets the result from the service and updates our list. The frequency at which we need to update the list can be set using number of properties as given in the documentation of quartz plugin.

Hope this helped.

Cheers!!
~~Amit Jain~~
amit@intelligrape.com
http://www.tothenew.com/blog/

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. amit

    Hi Rzezeski!
    I didn’t have to use any cache provider, to make use of a cron job. As this is not related to caching but we are making it work like cache provider for us.
    For definition of getRecentExcerptedPosts, you can refer to another blog

    Reply
  2. rzezeski

    I recently did something similar in an app I’m working on. At first I used springcache (and it worked with 1.1.1 for me, but it doesn’t seem to play well with acegi plugin) but what I didn’t like is that I only had the option to either add to the cache or flush it.

    In my scenario I wanted a Quartz job to kick off immediately, execute a “long running” query, and then cache those results. This way the users never have to take the latency hit of the query. Then the Quartz job runs every hour, runs the query again, and then sets the same key, which should happen as an atomic operation. If I would have used springcache I would have first flushed and then cached, but there would be a small window in between where the user could request the data and would take the full hit of the query.

    I ended up hooking into the already included ehcache provider. I just created a ehcache.xml and place it in my grails-app/conf.

    To my point, I’m curious as to what caching provider you used and what your getRecentExcerptedPosts method looks like.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *