Several methods to implement timing scheduling in Spring

  • 2020-06-07 04:33:47
  • OfStack

1. Introduction

The so-called timing scheduling refers to a mechanism adopted by the system to perform some specific functions at a certain time when no one is on duty. For traditional development, the operation of timing scheduling can be divided into two forms:

Timed trigger: To perform certain processing operations at a certain point in time;

Interval trigger: Automatic processing of certain operations after every few seconds.

All processing depends on the clock generator at the bottom of the computer system. In the initial implementation of java, there are two classes for timing processing: Timer and TimerTask. TimerTask mainly defines the execution of tasks, which is equivalent to starting a thread to execute some tasks.


public class MyTask extends TimerTask{

  @Override

  public void run() {// Define the tasks to be performed 

    // TODO Auto-generated method stub

    String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

    System.out.println(currentTime);

  } 

}

public class MyTaskTest {

  public static void main(String[] args) {

    Timer timer=new Timer();

    timer.schedule(new MyTask(), 1000);// Start the task, delay 1 Execute after seconds. 

  } 

}

However, if a task is required to be performed at a certain time, hour, and second of the year, Timer and TimerTask do not work. There are usually two options for timing control in project development:

quartz components: Enterprise and timing scheduling components that need to be configured separately;

SpringTask: Lightweight component with simple configuration that can be configured using Annotation.

2. Quartz defines timing scheduling

To use the Quartz component, we need to import the quartz development kit and add the quartz development kit to pom.xml.


<dependency>

      <groupId>org.quartz-scheduler</groupId>

      <artifactId>quartz</artifactId>

      <version>2.2.3</version>

</dependency>

With the package in place, the development of a scheduled schedule is ready.

There are two implementation patterns:

To inherit from the QuartzJobBean parent;

The method scheduling control can be realized by using configuration directly.

1. Inherit one parent class to realize the processing of tasks.


public class MyTask2 extends QuartzJobBean{

  @Override

  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

    // TODO Auto-generated method stub

        String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

        System.out.println(currentTime);

        System.out.println(" Specific task to achieve!! ");

  }

}

All timing tasks are enabled in the Spring control file, that is, there is no need to write an explicit class to enable timing tasks.

2. Add the configuration of timing scheduling in applicationContext.xml file, which is realized by the timing scheduling factory class.


<bean id="taskFactory"

    class="org.springframework.scheduling.quartz.JobDetailFactoryBean">

    <property name="jobClass" value="cn.wnh.timerSask.MyTask1" />

    <property name="jobDataMap">

      <map>

        <entry key="timeout" value="0" />

      </map>

    </property>

  </bean>

The triggering job for the task is then configured, with two types of job configuration:

Use interval trigger: repeat execution after several times;

The factory class: org springframework. scheduling. quartz. SimpleTriggerFactoryBean


<bean id="simpleTrigger"

    class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">

    <!--  Defines an executor class triggered by an interval  -->

    <property name="jobDetail" ref="taskFactory"></property>

    <!--  Set the timer trigger delay time  -->

    <property name="startDelay" value="0"></property>

    <!--  In milliseconds.  -->

    <property name="repeatInterval" value="2000"></property>

  </bean>

Set the interval trigger scheduler: org. springframework. scheduling. quartz. SchedulerFactoryBean


<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

    <property name="triggers">

      <list>

        <ref bean="simpleTrigger" />

      </list>

    </property>

  </bean>

3. At this point, all the interval trigger control is managed by Spring. Now, the interval trigger task can be realized only by starting the Spring container.

Timing triggering is implemented using Cron

Not only can Quartz trigger interval, it can also be combined with Cron to trigger timing, which is its most important function.

The most used patterns in general projects: hour trigger, month trigger, year trigger.

Modify the previous interval trigger configuration to use CronTriggerFactoryBean for timing trigger.


<bean id="taskFactory"

    class="org.springframework.scheduling.quartz.JobDetailFactoryBean">

    <property name="jobClass" value="cn.wnh.timerSask.MyTask1" />

    <property name="jobDataMap">

      <map>

        <entry key="timeout" value="0" />

      </map>

    </property>

  </bean>

  <bean id="cronTrigger"

    class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">

    <property name="jobDetail" ref="taskFactory" />

    <!-- cron Expression describing the trigger per minute 1 time  -->

    <property name="cronExpression" value="0 * * * * ?" />

  </bean>

  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

    <property name="triggers">

      <list>

        <ref bean="cronTrigger" />

      </list>

    </property>

  </bean>

This is done by starting the Spring container.

2. It does not inherit any class to realize timing scheduling

In project development, inheritance directly leads to the limitation of single inheritance, so in this case, Spring provides a task handling that can implement timed operations without inheriting any classes.

Defines a task execution class that does not inherit from any class.


public class MyTask2 {

  public void taskSelf(){

    String task=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date());

    System.out.println(task);

    System.out.println(" Perform specific task operations ");

  }

}

In applicationContext. xml in configuration factory class: org. springframework. scheduling. quartz. MethodInvokingJobDetailFactoryBean


<bean id="taskFactory2"

    class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

    <property name="targetObject">

      <bean class="cn.wnh.timerSask.MyTask2" />

    </property>

    <!-- Configure the methods to execute  -->

    <property name="targetMethod" value="taskSelf" />

  </bean>

The new program class is then configured on the task scheduling configuration


<bean id="cronTrigger"

    class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">

    <property name="jobDetail" ref="taskFactory2" />

    <!-- cron Expression describing the trigger per minute 1 time  -->

    <property name="cronExpression" value="* * * * * ?" />

  </bean>

Start the container to achieve the timing schedule.

This pattern has no class inheritance dependency and is more flexible to handle.

Spring Task implements timing scheduling

Spring has its own support for scheduling, which makes it even easier to use than Quartz.

There are two ways to implement it: 1. Configure the implementation in ES131en.xml; 2. 2. Annotation.

However, to use any pattern, you must first have a task handler class.

Define the task handler class.

The previous MyTask2 class is used instead of repeating.

Modify applicationContext. xml file:

Namespace definitions that need to be appended to task processing:


<dependency>

      <groupId>org.quartz-scheduler</groupId>

      <artifactId>quartz</artifactId>

      <version>2.2.3</version>

</dependency>
0

1 Configure the configuration of task operation to achieve interval triggering.


<dependency>

      <groupId>org.quartz-scheduler</groupId>

      <artifactId>quartz</artifactId>

      <version>2.2.3</version>

</dependency>
1

cron is used for timing triggering


<dependency>

      <groupId>org.quartz-scheduler</groupId>

      <artifactId>quartz</artifactId>

      <version>2.2.3</version>

</dependency>
2

As you can see, SpringTask is much simpler to implement.


Related articles: