Implementing Quartz Timers

 

1----------------------------------------------------------------------------

Quartz is a well-known Java version of the open source timing scheduler, powerful and easy to use.
 
1. The core concept
 
The principle of Quartz is not very complicated, as long as you understand a few concepts, and then know how to start and close a scheduler.
 
1. Job
represents a job, the specific content to be executed. There is only one method in this interface
void execute(JobExecutionContext context)
 
2. JobDetail
JobDetail represents a specific executable scheduler, Job is the content to be executed by the executable scheduler, and JobDetail also includes the task scheduling scheme and Strategy.

 
3. Trigger represents the configuration of a scheduling parameter, when to adjust it.
 
4. Scheduler represents a scheduling container, and multiple JobDetails and Triggers can be registered in a scheduling container. When the Trigger is combined with the JobDetail, it can be scheduled by the Scheduler container.
 
 
2. One of the simplest entry examples
 
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
* quartz定时器测试
*
* @author leizhimin 2009-7-23 8:49:01
*/
public class MyJob implements Job {
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                System.out.println(new Date() + ": doing something...");
        }
}

class Test {
        public static void main(String[] args) {
                //1. Create a JobDetial object
                JobDetail jobDetail = new JobDetail();
                //Set the work item
                jobDetail.setJobClass(MyJob.class);
                jobDetail.setName("MyJob_1" );
                jobDetail.setGroup("JobGroup_1");

                //2. Create a Trigger object
                SimpleTrigger strigger = new SimpleTrigger();
                strigger.setName("Trigger_1");
                strigger.setGroup("Trigger_Group_1");
                strigger.setStartTime(new Date());
                //Set the repeat stop time, And destroy the Trigger object
                java.util.Calendar c = java.util.Calendar.getInstance();
                c.setTimeInMillis(System.currentTimeMillis() + 1000 * 1L);
                strigger.setEndTime(c.getTime());
                strigger. setFireInstanceId("Trigger_1_id_001");
                //Set the repeat interval time
                strigger.setRepeatInterval(1000 * 1L);
                //Set the number of repetitions
                strigger.setRepeatCount(3);

                //3. Create a Scheduler object and configure JobDetail and Trigger objects
                SchedulerFactory sf = new StdSchedulerFactory();
                Scheduler scheduler = null;
                try {
                        scheduler = sf.getScheduler();
                        scheduler.scheduleJob(jobDetail, strigger);
                        //4, And perform operations such as startup, shutdown, etc.
                        scheduler.start();

                } catch (SchedulerException e) {
                        e.printStackTrace();
                }
// try {
// //shutdown the scheduler
// scheduler.shutdown(true);
// } catch (SchedulerException e) {
// e.printStackTrace() ;
// }
        }
}
 
Execution result:

 
When changing the end time to:
                //Set the repeat stop time and destroy the Trigger object
                java.util.Calendar c = java.util.Calendar.getInstance();
                c.setTimeInMillis(System.currentTimeMillis() + 1000 * 1L) ;
                strigger.setEndTime(c.getTime());
 
Execution result:
 
When adding a statement to close the scheduler:
                        //4, and perform operations such as startup and shutdown
                        scheduler.start();
                        scheduler.shutdown(true);

 
Program execution result:
Thu Jul 23 10:11:50 CST 2009: doing something...

Process finished with exit code 0
is executed only once, and this time it can be executed, because scheduler.shutdown(true); true means to wait for the completion of the execution of this task and stop.
 
It can also be seen from here that the scheduler is a container, the scheduler controls the execution of jobDetail, and the control strategy is through the trigger.
 
When the scheduler container is started, the jobDetail can be executed according to the associated trigger policy. When the scheduler container shuts down, all jobDetails stop executing.
 
Third, see the principle through the example
 
By studying the source code of Quartz, and this example, I finally realized the working principle of Quartz.
 
1. The scheduler is a plan scheduler container (headquarters). The container can hold many JobDetails and triggers. When the container is started, each JobDetail in it will be automatically executed step by step according to the trigger.
 
2. JobDetail is an executable job, which itself may be stateful.
 
3. Trigger represents the configuration of a scheduling parameter, when to adjust it.
 
4. After the JobDetail and Trigger are registered on the scheduler container, an assembled job (a pair composed of JobDetail and Trigger) is formed, which can be scheduled and executed with the container startup.
 
5. The scheduler is a container. There is a thread pool in the container, which is used to schedule and execute each job in parallel, which can improve the efficiency of the container.
 
6. The above structure is represented by a diagram, as follows:
 

 
4. Summary
 
1. Understand the principle and process of executing jobs on the Quartz container, as well as the way the job is formed, and the method of registering the job to the container. Just know and understand the core principle of Quartz.
 
2. Although Quartz is huge, everything revolves around this core. In order to configure a powerful time scheduling strategy, you can study a special CronTrigger. To flexibly configure job and container properties, you can do it through Quartz's properties file or XML.
 
3. To schedule more persistent and structured jobs, you can read jobs from the database and put them into containers for execution.
 
4. Everything revolves around this core principle. After understanding this, it is much easier to study more advanced usage.
 
5. The integration of Quartz and Spring is also very simple. Spring provides a set of beans to support: MethodInvokingJobDetailFactoryBean, SimpleTriggerBean, SchedulerFactoryBean, and you can see what properties need to be injected into it. Spring will start the Quartz container when the Spring container starts.
 
6. The way to close the Quartz container is also very simple. If it is Spring integration, there are two ways, one is to close the Spring container, the other is to get the SchedulerFactoryBean instance, and then call a shutdown to get it done. If Quartz is used independently, scheduler.shutdown(true) can be called directly;
 
7. Quartz's JobDetail and Trigger can be reset at runtime and will take effect at the next call. This provides the basis for the realization of dynamic jobs. You can store the scheduling time strategy in the database, and then set the Trigger through the database data, so that dynamic scheduling can be generated.

 

 

2--------------------------------------------------------------------------------------------------

There are two popular Spring timer configurations: Java's Timer class and OpenSymphony's Quartz.

1. Java Timer

first inherits the java.util.TimerTask class to implement the run method

import java.util.TimerTask;  
public class EmailReportTask extends TimerTask{
    @Override  
    public void run() {  
        ...  
    }    
}  
Defined in Spring

...

Configure Spring Timer

<bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">  
<property name="timerTask" ref="reportTimerTask" />  
<property name="period">  
<value>86400000value>  
property>  
bean>  
The timerTask property tells which ScheduledTimerTask to run. 86400000 represents 24 hours

to start the Spring timer

Spring's TimerFactoryBean is responsible for starting scheduled tasks

<bean class="org.springframework.scheduling.timer.TimerFactoryBean">  
<property name="scheduledTimerTasks">  
   <list><ref bean="scheduleReportTask"/>list>  
property>  
bean>  
scheduledTimerTasks Displays a list of timer tasks that need to be started.  
You can delay startup by setting the delay property  
<bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">  
<property name="timerTask" ref="reportTimerTask" />  
<property name="period">  
<value>86400000value>  
property>  
<property name="delay">  
<value>  






首先继承QuartzJobBean类实现executeInternal方法

import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  
import org.springframework.scheduling.quartz.QuartzJobBean;  

public class EmailReportJob extends QuartzJobBean{  
protected void executeInternal(JobExecutionContext arg0)  
throws JobExecutionException {  
...  
}  
}  
在Spring中定义

<bean id="reportJob" class="org.springframework.scheduling.quartz.JobDetailBean">  
<property name="jobClass">  
<value>EmailReportJobvalue>  
property>  
<property name="jobDataAsMap">  
    <map>  
        <entry key="courseService">  
            <ref bean="courseService"/>  
            entry>  
    map>  
property>  
bean>  
Here we do not directly declare an EmailReportJob Bean, but declare a JobDetailBean. This is the characteristic of Quartz. JobDetailBean is a subclass of Quartz's org.quartz.JobDetail, which requires a Job object to be set through the jobClass property.

Another special feature of using Quartz's JobDetail is that the courseService property of EmailReportJob is set indirectly. The jobDataAsMap property of JobDetail accepts a Map, including various properties set to jobClass, when. When the JobDetailBean is instantiated, it injects the courseService bean into the courseService property of the EmailReportJob.

Start Timer

Quartz's org.quartz.Trigger class describes when and how often to run a Quartz job. Spring provides two triggers SimpleTriggerBean and CronTriggerBean.
SimpleTriggerBean is similar to scheduledTimerTasks. Specifies the frequency of job execution, mimicking the scheduledTimerTasks configuration.

<bean id="simpleReportTrigger" class="org.springframework.scheduling.quartz.  






















1. Seconds 2. Minutes 3. Hours 4. Day of the month (1-31) 5. Month (1-12 or JAN-DEC) 6. Day of the week (1-7 or SUN-SAT) 7. Year (1970-2099)
Each element is displayed specifying a value (eg 6), a range (9-12), a list (9, 11, 13) or a wildcard (*). Because the two elements of 4 and 6 are mutually exclusive, you should set a question mark (?) to indicate which field you do not want to set, and "/" if the value is combined to indicate the number of repetitions (10/6 means repeat 6 every 10 seconds). Second-rate).

Start the timer

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
    <property name="triggers">  
       <list><ref bean="cronReportTrigger"/>list>  
    property>  
bean>  
The triggers property accepts a set of trigger.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484023&siteId=291194637