Spring integrates Quartz for dynamic timed tasks
Code repository address:Github.com/hanglegehan…
- Dynamically add scheduled tasks
- Example Modify a scheduled task
- Suspending a Scheduled Task
- Example Resuming a suspended scheduled task
What can Quartz be used for? Quartz is a task scheduling framework. Let’s say you have a problem like this
I want to pay my credit card automatically on the 25th of every month
I want to send an anonymous greeting card to my secret crush on April 1 every year
Want to backup your romantic action movie study notes to your cloud disk every hour
The problem boils down to doing something at a regular time. And the time trigger conditions can be so complex (such as 17:50 on the last business day of the month) that they require a dedicated framework to do it. Quartz is designed to do just that. You give it a definition of a trigger condition, and when it gets there, it triggers the Job.
But most of the time, we often meet the need of dynamic adding or modifying task, and provide in the spring’s timing task component can only by modifying the XML configuration of the trigger to control the timing of task time and task enabled or stop, this bring us convenient while also lost the flexibility of dynamic configuration tasks. Ideally, integration with Spring would allow dynamic tasks to be added, removed, and configured.
Ps: The project is based on Maven
Demonstration method: Deploy using Tomcat
1. Check the already deployed task 2 http://localhost:8080/list regularly. Initializes the timing task 3 http://localhost:8080/init. http://localhost:8080/stop 4 suspended regular task. Restore to suspend the timing of tasks at http://localhost:8080/resumeCopy the code
Spring/the spring XML configuration
- The traditional way
<! - use MethodInvokingJobDetailFactoryBean, task class can not achieve the Job interface, through targetMethod specified call methods - > < bean id ="taskJob" class="cn.huashantech.lawyer.service.DataConversionTask"/>
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <! --false: start a new task after the previous task has finished --> <property name="concurrent" value="false"/>
<property name="targetObject" ref="taskJob"/>
<property name="targetMethod" value="run"/> </bean> <! -- Scheduling trigger --> <bean id="myTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"/>
<property name="cronExpression" value="0/5 * * * *?"/>
</bean>Copy the code
- Configuration required for dynamic mode
<! -- Scheduling factory --> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">Copy the code
Core classes
cn.huashantech.lawyer.service.DynamicTask.Main
// Inject the scheduling factory with annotations
@Autowired
private Scheduler scheduler;Copy the code
www.cnblogs.com/drift-ice/p…
Reference source: blog.csdn.net/u014723529/…