The most popular Java backend framework is spring quartz timing tasks

  • 2020-04-01 04:27:41
  • OfStack

Configuring quartz in spring requires three jars:

Quartz -1.8.5.jar, Commons -collections-3.2.1.jar, Commons -logging-1.1.jar

The first step is to configure our spring.xml

XMLNS adds the following,

XMLNS: task = "(link: http://www.springframework.org/schema/task)"  

And then xsi:schemaLocation plus the following,

(link: http://www.springframework.org/schema/task)  
(link: http://www.springframework.org/schema/task/spring-task-3.1.xsd)  

Finally, our task task scan annotation

< Task: the annotation - driven / >  

My configuration scan location is:

<context:annotation-config/>  
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
    <context:component-scan base-package="com.test"/> 

Scanning the contents under a package like com.test,

The following is the interface and implementation (my several Java files are under the package of com.test,)


public interface IMyTestService { 
    public void myTest(); 
} 




@Component //import org.springframework.stereotype.Component; 
public class MyTestServiceImpl implements IMyTestService { 
   @Scheduled(cron="0/5 * * * * ? ")  //Execute every 5 seconds
   @Override 
   public void myTest(){ 
      System.out.println(" Enter the test "); 
   } 
} 

The console prints out   after execution;   Enter the test     the

A few points to note:

1. Spring @scheduled annotations   Need to be written on the implementation,

2, the timer task method cannot have a return value (if there is a return value, the spring initialization will tell you there is an error, need to set a proxytargetclass value is true, specific go to baidu Google bar)

3. Implement the class with the @component annotation

The rest is the corn expression, specific use and parameters please baidu Google,

[seconds]     [points]   [when]     "Day"   【 in 】       weeks 】 【 【 in 】    

So let's just do a couple of examples

CRON expression       meaning
"0, 0, 12 * * ?"       It triggers at noon every day
"0 15 10 & # 63; * * "      It triggers at 10:15 am every day
"0, 15, 10 * * ?"       It triggers at 10:15 am every day
"0, 15, 10 * * ? * "      It triggers at 10:15 am every day
"0, 15, 10 * * ? 2005 "      It was triggered every morning at 10:15 in 2005
"0 * 14 * * ?"       Every minute from 2 p.m. to 2:59 p.m. every day
"0 0/5 14 * * ?"       Every five minutes from 2 p.m. to 2:55 p.m
"0 0/5 14,18 * * ?"       The trigger occurs every five minutes between 2 p.m. and 2:55 p.m. and 6 p.m. and 6:55 p.m
"0, 0, minus 5, 14 * * ?"       Every minute from 14:00 to 14:05 every day
"0 10 44 14 & # 63; 3 WED "      Triggers are at 14:10 and 14:44 every Wednesday in March
"0 15 10 & # 63; * MON - FRI "      Every Monday, Tuesday, Wednesday, Thursday, Friday 10:15 triggers

Sometimes our jobs can't be done until certain tasks have been completed. For example, batch derivative data from the old database; Need to now import data that is dependent on other data into a new database; Then import the relationship. In this case, we can use the listener of the Quartz to do something.

First we write a class for the main task, called MainJob; Her role is as the starting point for a series of tasks.

MainJob. Java


package jobs;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MainJob extends QuartzJobBean {
private Logger logger=Logger.getLogger(getClass());
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
// TODO Auto-generated method stub
logger.debug("Just say hi.");
}

}

Then we create another task (SecondJob) as a follow-up:

SecondJob. Java


package jobs;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class SecondJob extends QuartzJobBean {
private Logger logger=Logger.getLogger(getClass());
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
// TODO Auto-generated method stub
logger.debug("I'm the second job.");
}

}

Create a TriggerListener, override its triggerComplete method, and add some properties and methods for spring injection.

NextJobTriggerListener. Java


package listeners;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.listeners.TriggerListenerSupport;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.scheduling.quartz.SimpleTriggerBean;

public class NextJobTriggerListener extends TriggerListenerSupport {
private Logger logger=Logger.getLogger(getClass());
private String name;
public String getName() {
return this.name;
}
public void setName(String name)
{
this.name=name;
}
private SimpleTriggerBean nextTrigger;
public void setNextTrigger(SimpleTriggerBean nextTrigger) {
this.nextTrigger=nextTrigger;
}
@Override
public void triggerComplete(Trigger trigger, JobExecutionContext context, int code) {
try{
Scheduler schduler=context.getScheduler();
JobDetail nextJob=nextTrigger.getJobDetail();
//Find a task with the same name as the task to be joined
JobDetail oldJob=schduler.getJobDetail(nextJob.getName(),nextJob.getGroup());
//Find the trigger with the same name as the one to be added
Trigger oldTrigger=schduler.getTrigger(nextTrigger.getName(),nextTrigger.getGroup());

if(oldJob==null&&oldTrigger==null)//Neither the task nor the trigger with the same name exists
{
logger.debug("inside scheduleJob."+code);
schduler.scheduleJob(nextJob,nextTrigger);
}else//A task or trigger with the same name
{

logger.debug("oldJob==null:"+(oldJob==null));
logger.debug("oldTrigger==null:"+(oldTrigger==null));
}
super.triggerComplete(trigger, context, code);
}catch(Exception e)
{
e.printStackTrace();
}
}


}

Configure spring's applicationcontext.xml

The applicationcontext.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:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!--  The main task  -->
<bean id="mainJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<!--  Operation of class  -->
<property name="jobClass">
<value> jobs.MainJob </value>
</property>
</bean>
<!--  Listener for the main task  -->
<bean id="mainTriggerListener"
class="listeners.NextJobTriggerListener">
<!--  Next trigger  -->
<property name="nextTrigger" ref="secondTrigger"></property>
<!--  Listener name  -->
<property name="name" value="mainTriggerListener"></property>
</bean>

<!--  Trigger for the main task  -->
<bean id="mainTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail">
<!--  The task scheduling object created above  -->
<ref bean="mainJob" />
</property>
<!--  Start the 60 The task is scheduled in seconds excute methods  -->
<property name="startDelay">
<value> 6000 </value>
</property>
<!--  Run number  -->
<property name="repeatCount">
<value> </value>
</property>
<!--  It runs every hour ( Seems to be redundant , Failure to write will result in an error ) -->
<property name="repeatInterval">
<value> 3600000 </value>
</property>
<property name="triggerListenerNames">
<list>
<value> mainTriggerListener </value>
</list>
</property>
</bean>
<!--  Subsequent task  -->
<bean id="secondJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<!--  Operation of class  -->
<property name="jobClass">
<value> jobs.SecondJob </value>
</property>
</bean>
<!--  Triggers for subsequent tasks  -->
<bean id="secondTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail">
<!--  The task scheduling object created above  -->
<ref bean="secondJob" />
</property>
<!--  Start the 6 The task is scheduled in seconds excute methods  -->
<property name="startDelay">
<value> 6000 </value>
</property>
<!--  Run number  -->
<property name="repeatCount">
<value> </value>
</property>
<!--  It runs every hour ( Seems to be redundant , Failure to write will result in an error ) -->
<property name="repeatInterval">
<!--
<value>3600000</value>
-->
<value> 6000 </value>
</property>
</bean>
<!--  Task scheduling factory class  -->
<bean
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!--  This part of the configuration is irrelevant  -->
<property name="quartzProperties">
<props>
<prop key="org.quartz.threadPool.class">
org.quartz.simpl.SimpleThreadPool
</prop>
<prop key="org.quartz.threadPool.threadCount"> </prop>
<prop key="org.quartz.threadPool.threadPriority">
</prop>
<prop
key="org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread">
true
</prop>
</props>
</property>
<!--  The trigger , You can put a bunch of triggers  -->
<property name="triggers">
<list>
<!--  Here to add  -->
<ref bean="mainTrigger"/>
</list>
</property>
<property name="triggerListeners">
<list>
<!--  The listener of the trigger  -->
<ref bean="mainTriggerListener" />
</list>
</property>
</bean>
</beans>

Open the server, output


DEBUG [ MainJob.executeInternal(14) ] Just say hi.
DEBUG [ NextJobTriggerListener.triggerComplete(38) ] inside scheduleJob .3
DEBUG [SecondJob.executeInternal(14)] I'm the second job.
DEBUG [ NextJobTriggerListener.triggerComplete(43) ] oldJob==null:false
DEBUG [ NextJobTriggerListener.triggerComplete(44) ] oldTrigger== null:false

In addition, a task is only bound with a simple trigger, which makes it easier to detect the completion of the task. As for the specific content of the task, let everyone play. Write this article in the hope that someone will be inspired by it.


Related articles: