Home >Java >javaTutorial >Several methods to implement timing scheduling in Spring
This article mainly introduces examples of timing scheduling in Spring. The system can perform certain functions at a certain time when no one is on duty. Those who are interested can learn more.
1, Content Introduction
The so-called scheduled scheduling refers to a mechanism by which the system can perform certain specific functions at a certain time when no one is on duty. For traditional In terms of development, scheduled scheduling operations are divided into two forms:
Scheduled triggering: perform certain processing operations at a certain point in time;
Interval triggering: performed every few seconds Automatic processing of certain operations.
All processing relies on the underlying clock generator of the computer system. In the initial implementation process of Java, there are two classes specifically provided for timing processing: Timer and TimerTask, of which TimerTask is mainly Defining the execution of tasks is equivalent to starting a thread to perform certain tasks.
public class MyTask extends TimerTask{ @Override public void run() {//定义要执行的任务 // 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);//启动任务,延迟1秒后执行。 } }
However, if you are required to perform a task at a certain time, minute and second in a certain month every year, there is nothing you can do using Timer and TimerTask. In project development, there are often two choices for timing control:
quartz component: enterprise and timing scheduling components, which need to be configured separately;
SpringTask: lightweight component, simple configuration, can Use Annotation to implement configuration processing.
2, Quartz defines timing scheduling
To use the Quartz component, we need to import the quartz development package and add the quartz development package in pom.xml.
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> </dependency>
After introducing the package, you can develop scheduled scheduling.
There are two implementation modes:
To inherit the QuartzJobBean parent class;
You can directly use the configuration to realize the scheduling control of the method.
1, inherit a parent class to implement task processing.
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("具体的任务实现!!!"); } }
All scheduled scheduling must be enabled in the Spring control file, that is, there is no need to write an explicit class to enable scheduled tasks. .
2. Add the scheduled scheduling configuration in the applicationContext.xml file and implement it through the scheduled 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>
Then configure the trigger job of the task. There are two types of job configurations:
Use interval trigger: repeat execution after a certain period of time;
Factory class: org.springframework.scheduling.quartz.SimpleTriggerFactoryBean
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <!-- 定义间隔触发的执行程序类 --> <property name="jobDetail" ref="taskFactory"></property> <!-- 设置定时触发延迟时间 --> <property name="startDelay" value="0"></property> <!-- 单位是”毫秒“ --> <property name="repeatInterval" value="2000"></property> </bean>
Set 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 time, all interval triggering controls are managed by Spring. Now you only need to start the Spring container to implement interval triggering tasks.
Use Cron to achieve scheduled triggering
Quartz can not only achieve interval triggering, it can also be combined with Cron to achieve scheduled triggering, which is also its most important function.
The most commonly used modes in general projects: trigger on the hour, trigger at the beginning of the month, and trigger at the beginning of the year.
Modify the previous interval trigger configuration and use CronTriggerFactoryBean to implement scheduled triggering.
<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>
Just start the Spring container.
2, do not inherit any class to implement timing scheduling
In project development, inheritance will directly lead to the limited control of single inheritance, so in this case, Spring provides a way to avoid Inheriting any class can implement task processing for scheduled operations.
Define a task execution class and do not inherit 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("执行具体任务操作"); } }
Configure the factory class in applicationContext.xml: org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
<bean id="taskFactory2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <bean class="cn.wnh.timerSask.MyTask2" /> </property> <!--配置要执行的方法 --> <property name="targetMethod" value="taskSelf" /> </bean>
Then configure a new program class in the task scheduling configuration
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="taskFactory2" /> <!-- cron表达式,描述每分钟触发一次 --> <property name="cronExpression" value="* * * * * ?" /> </bean>
Start the container to achieve scheduled scheduling.
This mode has no inheritance dependencies of classes, and the processing will be more flexible.
Spring Task implements scheduled scheduling
Spring has its own support for scheduled scheduling, and it feels even easier to use than Quartz.
It has two implementation methods, 1. Configure the implementation in applicationContext.xml; 2. Use Annotation to implement it.
But which mode to use, you must first have a task processing class.
Define task processing class.
The previous MyTask2 class is used directly here and will not be written again.
Modify the applicationContext.xml file:
Need to add a namespace definition for task processing:
<beans xmlns:task="http://www.springframework.org/schema/task" http://www.php.cn/ http://www.php.cn/ >
1 Configure task operation Configuration to achieve interval triggering.
<bean id="myTask" class="cn.wnh.timerSask.MyTask2" /> <task:scheduled-tasks> <task:scheduled ref="myTask" method="taskSelf" fixed-rate="2000" /> </task:scheduled-tasks>
Use cron to implement scheduled triggering
<bean id="myTask" class="cn.wnh.timerSask.MyTask2" /> <task:scheduled-tasks> <task:scheduled ref="myTask" method="taskSelf" cron="* * * * * ?" /> </task:scheduled-tasks>
It can be seen that SpringTask is simpler to implement .
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more related articles on several methods of implementing timing scheduling in Spring, please pay attention to the PHP Chinese website!