<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Quartz Scheduler</title>
	<atom:link href="http://www.javabeat.net/category/tools-ides/quartz-scheduler/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Quartz Job Scheduler &#8211; Example Code</title>
		<link>http://www.javabeat.net/2013/02/quartz-job-scheduler-example-code/</link>
		<comments>http://www.javabeat.net/2013/02/quartz-job-scheduler-example-code/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:37:31 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5943</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this section we are going to develop a simple Quartz Scheduler application with the help of Quartz framework. That will display &#8220;Hello World Quartz Scheduler :&#60;date &#38; time&#62;&#8221; on the console window after specified time schedule. Before using Scheduler you have to instantiate it. For doing this some users may keep an instance of [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>In this section we are going to develop a simple Quartz Scheduler application with the help of <b>Quartz</b> framework. That will display &#8220;<b><i>Hello World Quartz Scheduler :&lt;date &amp; time&gt;</i></b>&#8221; on the console window after specified time schedule.</p>
<p>Before using Scheduler you have to instantiate it. For doing this some users may keep an instance of a factory serialized in a <b>JNDI</b> store, and some other users may find it just to instantiate and use a factory instance. Firstly create the instance of <b>SchedulerFactory</b> by getting the reference of <i><b>org.Quartz.impl.StdSchedulerFactory </b></i>Class. Invoke the <b>getScheduler</b>() method by this instance to instantiate the <b>Scheduler</b>.</p>
<p><b>Description of code:</b></p>
<p><b>execute():</b> Any software components you want to schedule then you must implement the Job interface and override it execute() method.</p>
<p><b>JobExecutionContext:</b> The <b> JobExecutionContext</b> object that is passed to <b>execute</b>() method provides the job instance with information about its &#8220;run-time&#8221; environment &#8211; a handle to the Scheduler that executed it, a handle to the Trigger that triggered the execution, the job&#8217;s JobDetail object, and a few other items.</p>
<p><b>SchedulerFactory</b>: <b>SchedulerFactory</b> is a interface provides a mechanism for obtaining client-usable handles to <b> Scheduler</b> instances.</p>
<p><b>StdSchedulerFactory():</b> A Class <b>StdSchedulerFactory</b> is a class and it is implementation of <b>SchedulerFactory</b> interface. Here it just using for create an instance of <b>SchedulerFactory</b> instance.</p>
<p><b>Scheduler</b>: Scheduler interface is the main interface (<b>API</b>) to this functionality. It provides some simple operations like scheduling jobs, <b> unscheduling</b><b>jobs</b>, <b>starting</b>/<b>stopping</b>/<b>pausing</b> the scheduler.</p>
<p><b>getScheduler():</b><b>SchedulerFactoy</b> interface having the <b>getScheduler</b>() method that returns an instance of Scheduler.</p>
<p><b>start():</b> This method is used to starts the Scheduler&#8217;s threads that fire Triggers. At the first time when we create the Scheduler it is in &#8220;stand-by&#8221; mode, and will not fire triggers. The scheduler can also be send back into stand-by mode by invoking the <b>standby</b>() method.</p>
<p><b>JobDetail(String name, String group, Class jobclass):</b> The <b>JobDetail</b> object is created at the time the Job is added to scheduler. It contains various property settings like job name, group name and job class name. It can be used to store state information for a given instance of job class.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><b>SimpleTrigger(String name, String group, Date startTime, Date endTime, int repeatCount, long repeatInterval):</b> Trigger objects are used to firing the execution of jobs. When you want to schedule the job, instantiate the trigger and set the properties to provide the scheduling.</p>
<p><b>DEFAULT_GROUP:</b> It is a constant, specified that <b> Job</b> and <b> Trigger</b> instances are belongs to which group..</p>
<p><b>REPEAT_INDEFINITELY:</b> It is a constant used to indicate the &#8216;<b>repeat count</b>&#8216; of the trigger is indefinite.</p>
<p><b>scheduleJob(JobDetail jd, SimpleTrigger st):</b> This method is used to add the JobDetail to the Scheduler, and associate the Trigger with it.</p>
<p><b> Here is the code of Job Class:</b></p>
<div align="left">
<table border="0" cellspacing="0" cellpadding="3">
<tbody>
<tr>
<td align="left" valign="top" nowrap="nowrap"><code><code><b>import </b>org.quartz.Job;<br />
<b>import </b>org.quartz.JobExecutionContext;<br />
<b>import </b>org.quartz.JobExecutionException;<br />
<b>import </b>java.util.Date;</code></code><b>public class </b>HelloJob <b>implements </b>Job {<b>public </b><b>void </b>execute(JobExecutionContext arg0) <b>throws </b>JobExecutionException{</p>
<p>System.out.println(&#8220;Hello World Quartz Scheduler: &#8221; + <b>new </b>Date());<br />
}<br />
}</td>
</tr>
</tbody>
</table>
</div>
<p><a href="http://web.archive.org/web/20100612062411/http://www.roseindia.net/quartz/HelloJob.java"> </a></p>
<p><b>Here is the code of Scheduler Class:</b></p>
<p><code><b>import </b>java.util.Date;<br />
<b>import </b>org.quartz.JobDetail;<br />
<b>import </b>org.quartz.Scheduler;<br />
<b>import </b>org.quartz.SchedulerFactory;<br />
<b>import </b>org.quartz.SimpleTrigger;<br />
<b>import </b>org.quartz.impl.StdSchedulerFactory;</code></p>
<p><b>public class </b>HelloSchedule {<br />
<b>public </b>HelloSchedule()<b>throws </b>Exception{<br />
SchedulerFactory sf=<b>new </b>StdSchedulerFactory();<br />
Scheduler sched=sf.getScheduler();<br />
sched.start();<br />
JobDetail jd=<b>new </b>JobDetail(&#8220;myjob&#8221;,sched.DEFAULT_GROUP,HelloJob.<b>class</b>);<br />
SimpleTrigger st=<b>new </b>SimpleTrigger(&#8220;mytrigger&#8221;,sched.DEFAULT_GROUP,new Date(),<br />
null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L);<br />
sched.scheduleJob(jd, st);<br />
}<br />
<b>public static </b><b>void </b>main(String args[]){<br />
<b>try</b>{<br />
<b>new </b>HelloSchedule();<br />
}<b>catch</b>(Exception e){}<br />
}<br />
}</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Ftools-ides%2Fquartz-scheduler%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/tools-ides/quartz-scheduler/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/tools-ides/quartz-scheduler/feed/" data-count="vertical" data-text="Quartz Scheduler" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/quartz-job-scheduler-example-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quartz Interview Questions</title>
		<link>http://www.javabeat.net/2010/08/quartz-interview-questions/</link>
		<comments>http://www.javabeat.net/2010/08/quartz-interview-questions/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 00:38:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=451</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>What is Quartz? Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term &#8220;job scheduler&#8221; seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>What is Quartz?</h2>
<p>Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term &#8220;job scheduler&#8221; seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we use this term, but in short, a job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.</p>
<p>Quartz is quite flexible, and contains multiple usage paradigms that can be used separately or together, in order to achieve your desired behavior, and enable you to write your code in the manner that seems most &#8216;natural&#8217; to your project.</p>
<p>Quartz is very light-weight, and requires very little setup/configuration &#8211; it can actually be used &#8216;out-of-the-box&#8217; if your needs are relatively basic.</p>
<p>Quartz is fault-tolerant, and can persist (&#8216;remember&#8217;) your scheduled jobs between system restarts.</p>
<p>Although Quartz is extremely useful for simply running certain system processes on given schedules, the full potential of Quartz can be realized when you learn how to use it to drive the flow of your application&#8217;s business processes.<br />
What is Quartz &#8211; From a Software Component View?</p>
<p>Quartz is distributed as a small java library (.jar file) that contains all of the core Quartz functionality. The main interface (API) to this functionality is the Scheduler interface. It provides simple operations such as scheduling/unscheduling jobs, starting/stopping/pausing the scheduler.</p>
<p>If you wish to schedule your own software components for execution they must implement the simple Job interface, which contains the method execute(). If you wish to have components notified when a scheduled fire-time arrives, then the components should implement either the TriggerListener or JobListener interface.</p>
<p>The main Quartz &#8216;process&#8217; can be started and ran within your own application, as a stand-alone application (with an RMI interface), or within a J2EE app. server to be used as a resource by your J2EE components.</p>
<h2>Why not just use java.util.Timer?</h2>
<p>Since JDK 1.3, Java has &#8220;built-in&#8221; timer capabilities, through the java.util.Timer and java.util.TimerTask classes &#8211; why would someone use Quartz rather than these standard features?</p>
<p>There are many reasons! Here are a few:</p>
<p>1. Timers have no persistence mechanism.</p>
<p>2. Timers have inflexible scheduling (only able to set start-time &amp; repeat interval, nothing based on dates, time of day, etc.)</p>
<p>3. Timers don&#8217;t utilize a thread-pool (one thread per timer)</p>
<p>4. Timers have no real management schemes &#8211; you&#8217;d have to write your own mechanism for being able to remember, organize and retreive your tasks by name, etc.</p>
<p>&#8230;of course to some simple applications these features may not be important, in which case it may then be the right decision not to use Quartz.</p>
<h2>How can I control the instantiation of Jobs?</h2>
<p>See org.quartz.spi.JobFactory and the org.quartz.Scheduler.setJobFactory(..) method.</p>
<h2>How do I keep a Job from being removed after it completes?</h2>
<p>Set the property JobDetail.setDurability(true) &#8211; which instructs Quartz not to delete the Job when it becomes an &#8220;orphan&#8221; (when the Job not longer has a Trigger referencing it).</p>
<h2>How do I keep a Job from firing concurrently?</h2>
<p>Make the job class implement StatefulJob rather than Job. Read the JavaDOC for StatefulJob for more information.</p>
<h2>How do I stop a Job that is currently executing?</h2>
<p>See the org.quartz.InterruptableJob interface, and the Scheduler.interrupt(String, String) method.</p>
<h2>How do I chain Job execution? Or, how do I create a workflow?</h2>
<p>There currently is no &#8220;direct&#8221; or &#8220;free&#8221; way to chain triggers with Quartz. However there are several ways you can accomplish it without much effort. Below is an outline of a couple approaches:</p>
<p>One way is to use a listener (i.e. a TriggerListener, JobListener or SchedulerListener) that can notice the completion of a job/trigger and then immediately schedule a new trigger to fire. This approach can get a bit involved, since you&#8217;ll have to inform the listener which job follows which &#8211; and you may need to worry about persistence of this information.</p>
<p>Another way is to build a Job that contains within its JobDataMap the name of the next job to fire, and as the job completes (the last step in its execute() method) have the job schedule the next job. Several people are doing this and have had good luck. Most have made a base (abstract) class that is a Job that knows how to get the job name and group out of the JobDataMap using special keys (constants) and contains code to schedule the identified job. Then they simply make extensions of this class that included the additional work the job should do.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>In the future, Quartz will provide a much cleaner way to do this, but until then, you&#8217;ll have to use one of the above approaches, or think of yet another that works better for you.</p>
<h2>Why isn&#8217;t my trigger firing?</h2>
<p>The most common reason for this is not having called Scheduler.start(), which tells the scheduler to start firing triggers.</p>
<p>The second most common reason is that the trigger or trigger group has been paused.</p>
<h2>Daylight Saving Time and Triggers</h2>
<p>CronTrigger and SimpleTrigger each handle daylight savings time in their own way &#8211; each in the way that is intuitive to the trigger type.</p>
<p>First, as a review of what daylight savings time is, please read this resource: http://webexhibits.org/daylightsaving/g.html . Some readers may be unaware that the rules are different for different nations/contents. For example, the 2005 daylight savings time starts in the United States on April 3, but in Egypt on April 29. It is also important to know that not only the dates are different for different locals, but the time of the shift is different as well. Many places shift at 2:00 am, but others shift time at 1:00 am, others at 3:00 am, and still others right at midnight.</p>
<p>SimpleTrigger allows you to schedule jobs to fire every N milliseconds. As such, it has to do nothing in particular with respect to daylight savings time in order to &#8220;stay on schedule&#8221; &#8211; it simply keeps firing every N milliseconds. Regardless your SimpleTrigger is firing every 10 seconds, or every 15 minutes, or every hour or every 24 hours it will continue to do so. However the implication of this which confuses some users is that if your SimpleTrigger is firing say every 12 hours, before daylight savings switches it may be firing at what appears to be 3:00 am and 3:00 pm, but after daylight savings 4:00 am and 4:00 pm. This is not a bug &#8211; the trigger has kept firing exacly every N milliseconds, it just that the &#8220;name&#8221; of that time that humans impose on that moment has changed.</p>
<p>CronTrigger allows you to schedule jobs to fire at certain moments with respect to a &#8220;gregorian calendar&#8221;. Hence, if you create a trigger to fire every day at 10:00 am, before and after daylight savings time switches it will continue to do so. However, depending on whether it was the Spring or Autumn daylight savings event, for that particular Sunday, the actual time interval between the firing of the trigger on Sundary morning at 10:00 am since its firing on Saturday morning at 10:00 am will not be 24 hours, but will instead be 23 or 25 hours respectively.</p>
<p>There is one additional point users must understand about CronTrigger with respect to daylight savings. This is that you should take careful thought about creating schedules that fire between midnight and 3:00 am (the critical window of time depends on your trigger&#8217;s locale, as explained above). The reason is that depending on your trigger&#8217;s schedule, and the particular daylight event, the trigger may be skipped or may appear to not fire for an hour or two. As examples, say you are in the United States, where daylight savings events occur at 2:00 am. If you have a CronTrrigger that fires every day at 2:15 am, then on the day of the beginning of daylight savings time the trigger will be skipped, since, 2:15 am never occurs that day. If you have a CronTrigger that fires every 15 minutes of every hour of every day, then on the day daylight savings time ends you will have an hour of time for which no triggerings occur, because when 2:00 am arrives, it will become 1:00 am again, however all of the firings during the one o&#8217;clock hour have already occurred, and the trigger&#8217;s next fire time was set to 2:00 am &#8211; hence for the next hour no triggerings will occur.</p>
<h2>How do I improve the performance of JDBC-JobStore?</h2>
<p>There are a few known ways to speed up JDBC-JobStore, only one of which is very practical.</p>
<p>First, the obvious, but not-so-practical:<br />
* Buy a better (faster) network between the machine that runs Quartz, and the machine that runs your RDBMS.</p>
<p>* Buy a better (more powerful) machine to run your database on.</p>
<p>* Buy a better RDBMS.</p>
<p>Now for something simple, but effective: Build indexes on the Quartz tables.</p>
<p>Most database systems will automatically put indexes on the primary-key fields, many will also automatically do it for the foreign-key field. Make sure yours does this, or make the indexes on all key fields of every table manually.</p>
<p>Next, manually add some additional indexes: most important to index are the TRIGGER table&#8217;s &#8220;next_fire_time&#8221; and &#8220;state&#8221; fields. Last (but not as important), add indexes to every column on the FIRED_TRIGGERS table.</p>
<h2>Create Table Indexes</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">create index idx_qrtz_t_next_fire_time on qrtz_triggers(NEXT_FIRE_TIME);
create index idx_qrtz_t_state on qrtz_triggers(TRIGGER_STATE);
create index idx_qrtz_t_nf_st on qrtz_triggers(TRIGGER_STATE,NEXT_FIRE_TIME);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_group on qrtz_fired_triggers(TRIGGER_GROUP);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_n_g on qrtz_fired_triggers(TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(INSTANCE_NAME);
create index idx_qrtz_ft_job_name on qrtz_fired_triggers(JOB_NAME);
create index idx_qrtz_ft_job_group on qrtz_fired_triggers(JOB_GROUP);</pre></td></tr></table></div>

<h2>My DB Connections don&#8217;t recover properly if the database server is restarted.</h2>
<p>If you&#8217;re having Quartz create the connection data source (by specifying the connection parameters in the quartz properties file) make sure you have a connection validation query specified, such as:<br />
Connection Validation Query</p>
<p>org.quartz.dataSource.myDS.validationQuery=select 0 from dual</p>
<p>This particular query is extremly efficient for Oracle. For other databases, you&#8217;ll need to think of an efficient query that always works as long as the connection is good.</p>
<p>If you&#8217;re datasource is managed by your application server, make sure the datasource is configured in such a way that it can detect failed connections.</p>
<h2>I&#8217;m using JobStoreCMT and I&#8217;m seeing deadlocks, what can I do?</h2>
<p>JobStoreCMT is in heavy use, under heavy load by many people. It is believed to be free of bugs that can cause deadlock. However, every now and then we get complaints about deadlocks. In all cases thus far, the problem has turned out to be &#8220;user error&#8221;, thus the list below is some things for you to check if you are experiencing deadlocks.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">* Some databases falsely detect deadlocks when a tx takes a long time. Make sure you have put indexes on your tables (see improving performance of JDBCJobStore).
* Make sure you have at least number-of-threads-in-thread-pool + 2 connections in your datasources.
* Make sure you have both a managed and non-managed datasource configured for Quartz to use.
* Make sure that all work you do with the Scheduler interface is done from within a transaction. Accomplish this by using the Scheduler within a SessionBean that has its tx settings &quot;Required&quot; and &quot;Container&quot;. Or within a MessageDrivenBean with similar settings. Finally, start a UserTransaction yourself, and commit the work when done.
* If your Jobs' execute() methods use the Scheduler, make sure a transaction is in progress by using a UserTransaction or by setting the Quartz config propery &quot;org.quartz.scheduler.wrapJobExecutionInUserTransaction=true&quot;.</pre></td></tr></table></div>

<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/08/quartz-interview-questions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Job Scheduling support with JDK Timer and Quartz</title>
		<link>http://www.javabeat.net/2010/07/spring-job-scheduling-support-with-jdk-timer-and-quartz/</link>
		<comments>http://www.javabeat.net/2010/07/spring-job-scheduling-support-with-jdk-timer-and-quartz/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 00:24:50 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=441</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Not all applications are driven by user input. Some applications need to execute without any user intervention probably running at the background at specified intervals. For instance, a Virus Scanner application will be running in the background once in 2 days. Another instance could be where a Software could connect to its server repository once [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p align="justify">Not all applications are driven by user input. Some applications need to execute without any user intervention probably running at the background at specified intervals. For instance, a Virus Scanner application will be running in the background once in 2 days. Another instance could be where a Software could connect to its server repository once in a day for any updates. In this article we will see how Spring provides integration support for <strong><em>JDK Timer</em></strong> and <strong><em>Quartz</em></strong> that facilitates in writing job scheduling applications. The first half of the article draws an example for writing an application that uses <strong>JDK Timer with Spring support</strong>. The later section of the article discusses in writing an application that uses <strong>Quartz</strong> scheduling with some basic level of understanding done of cron expressions.</p>
<p align="justify"><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<blockquote>
<ul>
<li><a href="http://www.javabeat.net/category/web-frameworks/spring-mvc/">Spring Framework Article</a></li>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a> (recommended)</li>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-spring-mvc-web-framework-web-tier/">Introduction to Spring Framework</a></li>
<li><a title="Integrating Spring Framework with Hibernate ORM Framework" href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">Spring and Hibernate Integration</a></li>
</ul>
</blockquote>
<h2>Download Example Code for Spring Integration with JDK Timer and Quartz</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2010/spring-scheduling-with-quartz.zip">Spring Integration with Quartz and JDK Timer</a></li>
</ul>
<h2>Integrating JDK Timer with Spring Framework</h2>
<p align="justify">In this section, we will see how to integrate Spring with <strong><em>JDK Timer task objects</em></strong>. JDK Timer task objects provide support for execution of any task driven by a timer. Let us assume that we want to write a service that will periodically check for internet connection and logs the connection status. We will also imagine that this service has to run periodically all through the day with an interval of 30 minutes.</p>
<h3>Writing the service</h3>
<p align="justify">Following class provides the listing representing the internet connection service.</p>
<p><strong>InternetConnectionCheckService.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.spring.core.scheduling.timer;

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class InternetConnectionCheckService {

	public void checkConnection(){

		if (doCheck()){
			System.out.println(new Date() + &quot; Internet connection available&quot;);
		}else{
			System.out.println(new Date() + &quot; Internet connection not available&quot;);
		}
	}

	private boolean doCheck(){

		URL urlObject = null;
		URLConnection urlConnection = null;
		try{
			urlObject = new URL(&quot;http://www.google.com&quot;);
			urlConnection = urlObject.openConnection();
			urlConnection.getContent();
			return true;
		}catch (Exception exception){
			return false;
		}
	}
}</pre>
<p align="justify">The above code is fairly simple. To check whether internet connection is available or not it opens up a connection to a well-known domain for getting the content in the <code>doCheck()</code> method. When the connection is a failure, exception will be thrown which means that the connection is not available.</p>
<h3>Wrapping service as a timer task</h3>
<p align="justify">Now that we have written a service, we will see how to wrap the service as a task that can be driven from a timer. Refer the following code,</p>
<p><strong>InternetConnectionCheckTimerTask.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.spring.core.scheduling.timer;

import java.util.TimerTask;

public class InternetConnectionCheckTimerTask extends TimerTask{

	private InternetConnectionCheckService service;

	public InternetConnectionCheckService getService() {
		return service;
	}

	public void setService(InternetConnectionCheckService service) {
		this.service = service;
	}

	@Override
	public void run() {
		service.checkConnection();
	}

}</pre>
<p align="justify">We have written a timer task class which extends the <code>java.util.TimerTask</code> class. The <code>run()</code> method is overridden for performing any operation. In this case, the operation will be calling the internet connection service to check for the connection status. Note that timer task is dependant on internet connection service object. Later on, we will see how to wire both these objects.</p>
<h3>Configuration</h3>
<p align="justify">So far we haven&#8217;t specified the repeating interval of 30 minutes at which the service has to be executed. In fact, Spring already provides the support through configuration. Have a look at the following configuration file representing the application&#8217;s context.</p>
<p><strong>timer.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN 2.0//EN&quot; &quot;http://www.springframework.org/dtd/spring-beans-2.0.dtd&quot;&gt;

&lt;beans&gt;

	&lt;bean id=&quot;connectionCheckService&quot;&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;connectionCheckTimerTask&quot;&gt;
		&lt;property name=&quot;service&quot; ref=&quot;connectionCheckService&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;scheduledConnectionCheckTimerTask&quot;&gt;
		&lt;property name=&quot;delay&quot; value=&quot;2000&quot; /&gt;
		&lt;property name=&quot;period&quot; value=&quot;30000&quot; /&gt;
		&lt;property name=&quot;timerTask&quot; ref=&quot;connectionCheckTimerTask&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean&gt;
		&lt;property name=&quot;scheduledTimerTasks&quot;&gt;
		&lt;list&gt;
			&lt;ref bean=&quot;scheduledConnectionCheckTimerTask&quot;/&gt;
		&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p align="justify">We have declared the bean <code>connectionCheckService</code> representing the internet connection service. The second bean declaration defines the timer task with the bean id <code>connectionCheckTimerTask</code>. Because timer task is dependent on internet connection service, the dependency is injected through configuration.</p>
<p align="justify">Have a look at the following code snippet which declares the scheduled timer task object from Spring.</p>
<pre class="brush: java; title: ; notranslate">
&lt;bean id=&quot;scheduledConnectionCheckTimerTask&quot;&gt;
		&lt;property name=&quot;delay&quot; value=&quot;2000&quot; /&gt;
		&lt;property name=&quot;period&quot; value=&quot;30000&quot; /&gt;
		&lt;property name=&quot;timerTask&quot; ref=&quot;connectionCheckTimerTask&quot; /&gt;
&lt;/bean&gt;
</pre>
<p align="justify">This class <code>org.springframework.scheduling.timer.ScheduledTimerTask</code> provides scheduling support for the execution of timer tasks. The property <code>delay</code> specified in milliseconds specifies the initial delay after which the task has to be executed. The value is mentioned as <code>2000</code> which means after the initial delay for the execution of the task will be 2 seconds. Next comes the property <code>period</code> which is also specified in milliseconds and that represents the interval after which the task will be repeatedly execution. In our case, the value given is <code>3000</code>, so for every 30 minutes the task for execution will be fired. The final property is the <code>timerTask</code> which should point to the actual the timer task object, in this case it is going to be the <code>connectionCheckTimerTask</code>.</p>
<p align="justify">Triggering the scheduled tasks is done by <code>TimerFactoryBean</code>. It takes a list of scheduled timer task objects, in our case there is only one scheduled timer task object which is <code>scheduledConnectionCheckTimerTask</code>.</p>
<pre class="brush: java; title: ; notranslate">
&lt;bean&gt;
	&lt;property name=&quot;scheduledTimerTasks&quot;&gt;
		&lt;list&gt;
			&lt;ref bean=&quot;scheduledConnectionCheckTimerTask&quot;/&gt;
		&lt;/list&gt;
	&lt;/property&gt;
&lt;/bean&gt;
</pre>
<h3>Client</h3>
<p align="justify">The client application in this example is going to do nothing other than just loading the application&#8217;s context. As soon the context is loaded service object, timer task object, scheduled timer task objects will be loaded and wired. Because we have also introduced the trigger bean which will trigger the scheduled timer task for execution, the internet connection will be running indefinitely with an interval of 30 minutes.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><strong>Client.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.spring.core.scheduling.timer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(&quot;timer.xml&quot;);
	}
}</pre>
<h2>Spring Integration with Quartz</h2>
<p align="justify">In this section, we will see how to integrate <strong>Spring with Quartz scheduling support</strong>. <strong>Quartz</strong> is extremely robust and powerful with advanced features such as distributed transactions and persistent jobs, the scope of which is completely outside of this article. We will write an example which will trigger an application for receiving work status for all the employees on all the business days (i.e from Monday till Friday) at 11 AM and 6PM.</p>
<h3>Writing the service</h3>
<p align="justify">Since the focus is more on explaining the advanced scheduling support, this service will do nothing other than printing on the console that the service has been invoked at appropriate hours.</p>
<p><strong>StatusUpdateService.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.spring.core.scheduling.quartz;

import java.util.Date;

public class StatusUpdateService {

	public void updateStatus(){
		System.out.println(new Date() + &quot; Update status Service invoked&quot;);
	}
}</pre>
<h3>Wrapping service in a job bean</h3>
<p align="justify">A <strong><em>Job Bean</em></strong> in <strong>Quartz</strong> encapsulates the task for execution and in our case, the task is as simple as calling the status update service. Have a look at the status update job bean.</p>
<p><strong>StatusUpdateJobBean.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.spring.core.scheduling.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class StatusUpdateJobBean extends QuartzJobBean{

	private StatusUpdateService service;

	@Override
	protected void executeInternal(JobExecutionContext context)
		throws JobExecutionException {
		service.updateStatus();
	}

	public StatusUpdateService getService() {
		return service;
	}

	public void setService(StatusUpdateService service) {
		this.service = service;
	}

}</pre>
<p align="justify">Note that a job bean must extend QuartzJobBean and the method <code>executeInternal()</code> should be overridden for a job to execute. Note that later on in the configuration file we will see how the dependency between status update service and status update job bean is resolved.</p>
<h3>Configuration</h3>
<p align="justify">The configuration file provides the declaration of beans, wiring the dependency between beans as well the scheduling support for job execution. Have a look at the listing.</p>
<p><strong>quartz.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN 2.0//EN&quot; &quot;http://www.springframework.org/dtd/spring-beans-2.0.dtd&quot;&gt;

&lt;beans&gt;

	&lt;bean id=&quot;statusUpdateService&quot;&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;statusUpdateJob&quot;&gt;
		&lt;property name=&quot;jobClass&quot; value=&quot;net.javabeat.articles.spring.core.scheduling.quartz.StatusUpdateJobBean&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;statusUpdateTriggerBean&quot;&gt;
		&lt;property name=&quot;jobDetail&quot; ref=&quot;statusUpdateJob&quot;/&gt;
		&lt;property name=&quot;cronExpression&quot; value=&quot;0 0 11,18 ? * MON-FRI *&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean&gt;
		&lt;property name=&quot;triggers&quot;&gt;
			&lt;list&gt;
				&lt;ref bean=&quot;statusUpdateTriggerBean&quot;/&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p align="justify">The first bean declaration with the id <code>statusUpdateService</code> declares an instance of <code>StatusUpdateService</code> service which has the core logic for the execution of a job. Next comes the declaration of <code>JobDetailBean</code> which is declared as follows,</p>
<pre class="brush: java; title: ; notranslate">
&lt;bean id=&quot;statusUpdateJob&quot;&gt;
&lt;property name=&quot;jobClass&quot; value=&quot;net.javabeat.articles.spring.core.scheduling.quartz.StatusUpdateJobBean&quot; /&gt;
&lt;/bean&gt;
</pre>
<p align="justify">The mandatory property for this job bean is <code>jobClass</code>. The property <code>jobClass</code> takes the fully qualified name of the <code>JobBean</code> which acts as wrapper in delegating the call to the real task of execution, in our case, the class name is <code>net.javabeat.articles.spring.core.scheduling.quartz.StatusUpdateJobBean</code>.</p>
<p align="justify">Next comes the declaration of the CronTriggerBean which will be acting as a scheduler providing the time period and interval on which the job has to be executed. This bean takes the mandatory properties <code>jobDetail</code> and <code>cronExpression</code>. The property <code>jobDetail</code> takes a reference to the job detail object that was just declared. The <code>cronExpression</code> property specifies the interval at which the job has to be executed. Here the value given is &#8220;0 0 11,18 ? * MON-FRI *&#8221;. This value has 7 parts with space as a delimiter the meaning of which is given as follows</p>
<ul>
<li>First Field – Seconds</li>
<li>Second Field – Minutes</li>
<li>Third Field – Hours</li>
<li>Fourth Field – Day of the Month</li>
<li>Fifth Field – Month</li>
<li>Sixth Field – Day of week</li>
<li>Seventh Field – Year</li>
</ul>
<p align="justify">Every value in the field can either take a single value (Eg: 1), comma-separated (Eg: 1,3,5) or range-based (Eg: 1-10). There are <strong><em>wild-card charactes</em></strong> &#8216;*&#8217; and &#8216;?&#8217; carrying special meaning. When &#8216;*&#8217; is used against a field, it indicates all the values. For example, when &#8216;*&#8217; is used for the third field, then it mean for all hours or for every hours. When &#8216;?&#8217; is used it indicates that the field doesn&#8217;t carry any value.</p>
<p align="justify">So, coming back to our example, the value specified is &#8220;0 0 11,18 ? * MON-FRI *&#8221; which means &#8220;For every second in every minute, but during the hours 11 AM and 6 PM (not considering any day in a month), for all the months ranging from Monday till Friday in every Year&#8221; execute the given task.</p>
<p align="justify"><strong>also read:</strong></p>
<blockquote>
<ul>
<li><a href="http://www.javabeat.net/category/web-frameworks/spring-mvc/">Spring Framework Article</a></li>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a> (recommended)</li>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-spring-mvc-web-framework-web-tier/">Introduction to Spring Framework</a></li>
<li><a title="Integrating Spring Framework with Hibernate ORM Framework" href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">Spring and Hibernate Integration</a></li>
</ul>
</blockquote>
<h2>Conclusion</h2>
<p align="justify">We have seen how to write <strong><em>Job Scheduling applications</em></strong> with <strong><em>JDK Timer and Quartz</em></strong> objects with the help of Spring. It can be seen that for an application requiring basic scheduling support, it is wise to choose <strong>JDK Timer</strong>, however for applications that requires more sophisticated scheduling support; it is preferable to choose <strong>Quartz</strong>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/07/spring-job-scheduling-support-with-jdk-timer-and-quartz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
