Misc

Easy Method Scheduler with Spring 3.x

Scheduling by Annotation

The Java community is wide, and sometimes its easy to miss something simple. But always “google it first”, if you are doing something and it seems harder than it should, you’re probably doing it wrong. So today, lets go ahead an schedule a re-occurring process in a Jersey REST service.

Use Case: Updating cached values every (N) period

Say you have a website that needs to be responsive, but it needs to “call home” every-now-and-then to make sure it’s running with the latest settings and data. In effect you want an expiring cache that should expire every (N) period (TTL or Total Time To Live). With java and spring this is super easy.

Code

We need a public method that does not return a value and we need to define the period. Spring has many options (http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html) for defining the period; from cron, to fixed interval, etc. In this instance I am choosing fixedRate which will allow the method to execute and it will not restart the timer till the method completes (so if the refresh operation takes awhile we wont overlap executions).

private static int TEN_MINUTES = 1000 * 60 * 10;
@Scheduled(fixedRate = TEN_MINUTES)
public void refresh() {
   // ... do something cool to update your cache/data
}

Spring

Now we add our spring information and, low-and-behold, we’ll have automated polling! It really is that easy!

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
    <task:executor id="myExecutor" pool-size="5"/>
    <task:scheduler id="myScheduler" pool-size="10"/>

</beans>
Standard

Leave a Reply

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