Using JDK Timer support - Java-Springs

The other way to schedule jobs in Spring is to use JDK Timer objects. You can create custom timers or use the timer that invokes methods. Wiring timers is done using the TimerFactoryBean.
Creating custom timers
Using the TimerTask you can create customer timer tasks, similar to Quartz jobs:

public class CheckEmailAddresses extends TimerTask {
private List emailAddresses;
public void setEmailAddresses(List emailAddresses) {
this.emailAddresses = emailAddresses;
public void run() {
// iterate over all email addresses and archive them
Wiring it up is simple:
<bean id="checkEmail" class="examples.
<property name="emailAddresses">
<bean id="scheduledTask" class="org.springframework.
<!-- wait 10 seconds before starting repeated execution -->
<property name="delay" value="10000" />
<!-- run every 50 seconds -->
<property name="period" value="50000" />
<property name="timerTask" ref="checkEmail" />

Note that letting the task only run once can be done by changing the period property to 0 (or a negative value).

Using the MethodInvokingTimerTaskFactoryBean
Similar to the Quartz support, the Timer support also features a component that allows you to periodically invoke a method:

<bean id="doIt"class="org.springframework.scheduling. timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject"ref="exampleBusinessObject" />
<property name="targetMethod"value="doIt" />

The above example will result in the doIt method being called on the exampleBusinessObject (see below):

public class BusinessObject {
// properties and collaborators
public void doIt() {
// do the actual work

Changing the timerTask reference of the ScheduledTimerTask example to the bean doIt will result in the doIt method being executed on a fixed schedule.

Wrapping up: setting up the tasks using the TimerFactoryBean
The TimerFactoryBean is similar to the Quartz SchedulerFactoryBean in that it serves the same purpose: setting up the actual scheduling. The TimerFactoryBean sets up an actual Timer and schedules the tasks it has references to. You can specify whether or not daemon threads should be used.

<bean id="timerFactory" class="org.springframework.
<property name="scheduledTimerTasks">
<!-- see the example above -->
<ref bean="scheduledTask" />

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Java-Springs Topics