Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling Task in Spring/Java

I am spawning a thread which will keep pulling the chunk of records from database and putting them into the queue. This thread will be started on the server load. I want this thread to be active all the time. If there are no records in the database I want it to wait and check again after some time. I was thinking of using spring task scheduler to schedule this but not sure if that is right because I only want my task to be started once. What will be the good way of implementing this in Spring ?

Also, i need to have a boundary check that if my thread goes down (because of any error or exception condition) it should be re-instantiated after some time.

I can do all this in java by using thread communication methods but just trying if there is something available in Spring or Java for such scenarios.

Any suggestions or pointer will help.

like image 561
Ashu Avatar asked Mar 19 '13 22:03

Ashu


1 Answers

You can use the @Scheduled annotation to run jobs. First create a class with a method that is annotated with @Scheduled.

Class

public class GitHubJob {

   @Scheduled(fixedDelay = 604800000)
   public void perform() {
      //do Something
    }
}

Then register this class in your configuration files.

spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<tx:annotation-driven/>
<task:annotation-driven scheduler="myScheduler"/>

<task:scheduler id="myScheduler" pool-size="10"/>
<bean id="gitHubJob" class="org.tothought.spring.jobs.GitHubJob"/>

</beans>

For more about scheduling visit the Spring Docs.

like image 61
Kevin Bowersox Avatar answered Oct 18 '22 22:10

Kevin Bowersox