ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Spring integration with other technology or frameworks

Updated on July 20, 2009

Spring and Quartz Timer

I will not talk more about spring or quartz. I am assuming that you must know spring and quartz. I will explain you how to integrate quartz with Spring framwork.

First i will show you how to create timer using quartz.

Quartz offers five main classes/Interfaces for scheduling:

  • The Job interface
  • The JobDetail class
  • The Trigger abstract class
  • The Scheduler interface
  • The SchedulerFactory interface

The Job interface represents a job. A job offers what task or work you want to perform. Only one execute() method, which will be called by Quartz when a Job has to be executed. You can retrieve info like job name, trigger and many more info from JobExecutionContext that is passed to the execute() method. Below example shows sample job class.

public class MyJob implements Job {
	public void execute (JobExecutionContext ctx) throws JobExecutionException {
		System.out.println("Welcome Chirag");
	}
}


>>

>

The JobDetail class is for giving some information about a particular Job. Jobs will be started (or "fired") by triggers, which are represented by the Trigger class which are SimpleTrigger and CronTrigger. A SimpleTrigger is a basic timer, where we can declare a start time, an end time, no of times repeated and after what time it should be repeated. Second trigger is CronTrigger in which we can declare complex timer declaration, using the "cron" like Unix cron job notation. E.g. "fire the job at 1:15am on every Tuesday in january". Last one is the SchedulerFactory which is used to get a instance of Scheduler, using which we can register jobs and triggers.

public class MyJobMain {
public static void main (String[] args) {		
   try {
	SchedulerFactory schedFactory = new StdSchedulerFactory();

	Scheduler mySched = schedFactory.getScheduler();
        mySched.start();
			
	JobDetail jobDetail = new JobDetail("MyJob", null, MyJob.class);
	// Fires every 50 seconds
	Trigger trigger = TriggerUtils.makeSecondlyTrigger(50); 
	trigger.setName("myTrigger");
			
	mySched.scheduleJob(jobDetail, trigger);
	} catch (SchedulerException ex) {
	   ex.printStackTrace();
	}
    }
}

Output: 
After executing above program Welcome Chirag is being printed out every 50 seconds.

Now We will look quartz integration with Spring step by step

1) Classes provided by Spring for Quartz

  • The QuartzJobBean abstract class
  • The JobDetailBean class
  • The SimpleTriggerBean class
  • The CronTriggerBean class
  • The SchedulerFactoryBean class
  • The MethodInvokingJobDetailFactoryBean class
All above classes are more or less same as quartz API except MethodInvokingJobDetailFactoryBean whch has 
one advantage that we will see in last section.

2) How to declare jobs in spring context using JobDetailBean

The JobDetailBean is used to specify jobs that we want to execute. We can 
set the name of the job class. The Spring Framework provides a JobDetailBean
that makes the JobDetail more of an actual JavaBean with sensible defaults. .
Here is the declaration : 

<bean name="myJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="com.test.MyJob" />
  <property name="jobDataAsMap">
    <map>
      <entry key="tips" value="Welcome Chirag" />
    </map>
  </property>
</bean>

And the declaration job class which is extending QuartzJobBean class and overriding executeInternal method. We can customize this job class and method using MethodInvokingJobDetailFactoryBean that we will look in last section :

public class MyJob extends QuartzJobBean {
	private String message;
	
	public void setMessage (String message) {
		this.message = message;	
	}

	@Override
	protected void executeInternal (JobExecutionContext ctx) throws JobExecutionException {
		String tips = (String) ctx.getJobDetail().getJobDataMap().get("tips");
		System.out.println("Message comes from context:" + tips);
	}
}
3) How to declare triggers in spring context using SimpleTriggerBean or CronTriggerBean

Now We have created job details and jobs. Now time to schedule the jobs themselves. This is done using triggers and a SchedulerFactoryBean like we did in simple quartz without using spring framework.

Triggers need to be scheduled. Spring offers a SchedulerFactoryBean that exposes triggers to be set as properties. SchedulerFactoryBean job is to schedule the actual jobs with using triggers.

Find below examples of simple and cron trigger:

<bean id="mySimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <property name="jobDetail" ref="myJob" />
    <property name="startDelay" value="5" />
    <!-- This will run after every 5 seconds -->
    <property name="repeatInterval" value="5000" />
</bean>

<bean id="myCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="myJob" />
    <!-- It will run onevery morning at 10 AM -->
    <property name="cronExpression" value="0 0 10 * * ?" />
</bean>

Now we have declared two triggers, one running every 5 seconds with a starting delay of 5 seconds and second cron trigger running on every morning at 10 AM.

4) Schedule schedular using above job and trigger defined in Spring context

Now we have declared job and associated trigger, its time to register the
trigger. We will declare Spring's SchedulerFactoryBean the following way :

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
        <list>
            <ref bean="mySimpleTrigger"/>
        </list>
    </property>
</bean>	


>>

Now Everything has been set up, all we need now is to load the context. The scheduler will be started automatically on initialization. I declared all the above beans in a file called"spring-quartz.xml".Now if you want to use crontrigger then just change the reference bean name in trigger list. you can define list of triggers but job name should be unique.

public class MyJobMain {
	public static void main (String[] args) throws SchedulerException {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-quartz.xml");
	}
}

Executing above MyJobMain program will start the scheduler automatically. As per our declaration The MyJob will be fired after 5 seconds of delay and repeated after every 5 seconds.

5) Use spring's MethodInvokingJobDetailFactoryBean 

Many times we want to invoke a method on a specific class object. For that spring provides MethodInvokingJobDetailFactoryBean :

<bean id="myCustomJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="myCustomJobTest" /> <property name="targetMethod" value="testIt" /> </bean>

The above example will result in the testIt method being called on the myCustomJobtest See below code for example

public class MyCustomJobtest { // properties public void testIt() { // do your job work } } <bean id="myCustomJobtest" class="com.test.MyCustomJobtest"/>

Using the MethodInvokingJobDetailFactoryBean, you don't need to create one-line jobs that just invoke a method, and you only need to create the actual business object and wire up the detail object.

One more property provided by spring in MethodInvokingJobDetailFactoryBean is non-concurrent, set the concurrent flag to false.

That's all for today. Will come back with other technology with Spring.

 

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)