Knowledge changes fate, masturbation makes me happy, how is your hair line in 2019? This article corresponds to the source code cloud (Gitee) warehouse gitee.com/minbox-proj… Your Star is the biggest motivation for me

Quartz is an excellent task scheduling framework that supports in-memory, JDBC storage of unexecuted task lists, simultaneous execution of multiple task nodes, and task shifting to different nodes for execution.

preface

I think such an excellent task scheduling framework should be the preferred solution for many developers, so ApiBoot starts with it. Based on SpringBoot, a component named ApiBoot Quartz is encapsulated, and the initial integration can be easily realized in the form of application. Yml configuration file.

ApiBoot Quartz also provides an interface for frequently used methods, such as create task, pause task, restore task, delete task, and so on.

ApiBoot links required for this article:

  • ApiBoot website
  • ApiBoot full component series of articles
  • ApiBoot Gitee Source Repository (welcome Contributor)
  • ApiBoot GitHub source repository (welcome Contributor)

Task storage mode

Quartz itself offers two ways to store tasks:

  • Memory: Memory mode: Stores tasks in memory. The tasks will be lost when the project restarts. This mode is not recommended for production environments.
  • Jdbc: In database mode, tasks are stored toQuartzFixed structure provided in the table, the project restart task will not be lost, a variety of database construction sentences please visit:Quartz SchemasSelect on demand.

The ApiBoot encapsulates the two storage modes provided in Quartz and is configured using the api.boot.Quartz. Job-storetype parameter, which defaults to memory, so this parameter does not need to be changed if you use the memory mode. For more configuration, visit ApiBootQuartzProperties.

Task type

Task types are a new concept of ApiBoot Quartz. In Quartz, there is no type distinction between tasks. Implementing the org.Quartz.

But Spring is also a bit of a mess, and it wraps it up with QuartzJobBean, which is an abstract class that we can also inherit to create a scheduled task.

There are three task types in ApiBoot Quartz, which are:

  • OnceJob: Indicates the type of the job that is executed only once
  • CronJob: The Cron expression is used to define the execution period of a task
  • LoopJob: indicates that the task can be executed repeatedly according to the specified number of cycles

Built-in methods

ApiBoot encapsulation methods are provided after the Quartz in ApiBootQuartzService interface, the interface has a default implementation class ApiBootQuartzServiceDefaultSupport, all the implementation class implements an interface definition method, Scheduler uses org.Quartz.Scheduler internally to implement basic tasks.

List of built-in methods:

methods describe
Scheduler getScheduler(); Gets a Scheduler instance within the SpringIoc container
String newJob(ApiBootJobWrapper jobWrapper); Create a new task from the encapsulated object, which is the entry point for creating all types of tasks
void deleteJob(String jobKey); Deleting a Task
void deleteJobs(String… jobKeys); Delete a series of tasks
void deleteJobs(Collection jobKeys); Delete all tasks in the collection
void pauseJob(String jobKey); Pause a task
void pauseJobs(String… jobKeys); Suspend all tasks passed
void pauseJobs(Collection jobKeys); Pause all tasks in the collection
void resumeJob(String jobKey); Example Restore a task
void resumeJobs(String… jobKeys); Restores all task execution in array
void resumeJobs(Collection jobKeys); Resume all task execution in the collection
void updateJobCron(String jobKey, String cron); Update the task Cron expression
void updateJobStartTime(String jobKey, Date jobStartTime); Update the task start time
void startAllJobs(); Example Start all scheduled tasks
void shutdownAllJobs(); None example Disable all scheduled tasks

Now that ApiBoot provides us with so many built-in methods, let’s create a project to get a feel for it.

The sample project

Using Idea to create a SpringBoot project, we add the dependencies needed in this chapter to the pom.xml file, as shown below:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <! --ApiBoot Quartz-->
  <dependency>
    <groupId>org.minbox.framework</groupId>
    <artifactId>api-boot-starter-quartz</artifactId>
  </dependency>
</dependencies>
<dependencyManagement>
  <dependencies>
    <! ApiBoot unified version -->
    <dependency>
      <groupId>org.minbox.framework</groupId>
      <artifactId>api-boot-dependencies</artifactId>
      <version>2.2.1. RELEASE</version>
      <scope>import</scope>
      <type>pom</type>
    </dependency>
  </dependencies>
</dependencyManagement>
Copy the code

Note: ApiBoot versions are defined according to SpringBoot versions, as shown in the ApiBoot version branch

Sample task class

Let’s create a task scheduling example class called DemoJob, as follows:

/** * Example task **@authorHeng Yu Teenager */
public class DemoJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Mission carried out..."); }}Copy the code

What is QuartzJobBean?

QuartzJobBean QuartzJobBean QuartzJobBean QuartzJobBean is provided by Spring and implements org.Quartz.Job interface, which is an implementation and encapsulation of the Built-in Quartz task interface.

The advantage of QuartzJobBean

What are the specific advantages of Spring’s QuartzJobBean?

  • Automatically add implementation class instances to IOC

    When you use QuartzJobBean to create a custom task, Spring automatically scans the implementation classes within the project, creates instances of each implementation class through reflection and writes the instances to the IOC container.

  • Instances can be injected within the implementation class

    If the custom task instance is not added to the IOC container, we cannot inject Service into the custom task class. For those of you who know the basics of Spring, we cannot inject Service into a class that is not managed by IOC. With QuartzJobBean, you don’t have to worry about this.

QuartzJobBean registration process

Why not add task implementation classes to the IOC container manually after using ApiBoot Quartz?

The task class registration process is as follows:

  • The first step: ApiBootQuartzAutoConfiguration# quartzScheduler ()

    ApiBoot when integrated Quartz ApiBootQuartzAutoConfiguration provides an automated configuration class, in the class by quartzScheduler () method to automatically create a SchedulerFactoryBean instance

  • SchedulerFactoryBean#setJobFactory()

    The setJobFactory() method provided in SchedulerFactoryBean allows you to customize the implementation class that uses JobFactory, which is already provided in the Spring-Context-support dependency. Called SpringBeanJobFactory.

  • SpringBeanJobFactory#createJobInstance()

    When the project starts, all the QuartzJobBean implementation classes will be scanned to create task instances through JobFactory#newJob method, which will be delivered to the Quartz framework for later task scheduling.

The SpringBeanJobFactory class inherits from the AdaptableJobFactory class, which implements the JobFactory interface. So if we set SpringBeanJobFactory to SchedulerFactoryBean project startup Quartz will call the SpringBeanJobFactory#createJobInstance() method to create the task instance.

In the createJobInstance() method, Spring stores the created task instance into the IOC container so that we can inject other beans into our custom task.

/** * Create the job instance, populating it with property values taken * from the scheduler context, job data map and trigger data map. */
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
  Object job = (this.applicationContext ! =null ?
                // Create a task instance through ApplicationContext and add it to IOC
                this.applicationContext.getAutowireCapableBeanFactory().createBean(
                  bundle.getJobDetail().getJobClass(), AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false) :
                super.createJobInstance(bundle));

  if (isEligibleForPropertyPopulation(job)) {
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
    MutablePropertyValues pvs = new MutablePropertyValues();
    if (this.schedulerContext ! =null) {
      pvs.addPropertyValues(this.schedulerContext);
    }
    pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
    pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
    if (this.ignoredUnknownProperties ! =null) {
      for (String propName : this.ignoredUnknownProperties) {
        if(pvs.contains(propName) && ! bw.isWritableProperty(propName)) { pvs.removePropertyValue(propName); } } bw.setPropertyValues(pvs); }else {
      bw.setPropertyValues(pvs, true); }}return job;
}
Copy the code

This is what the QuartzJobBean implementation class registration process looks like. Let’s see if it’s really that easy to create and execute a task.

Run the test

For demonstration purposes, we modify the XxxApplication entry class to automatically execute the DemoJob task after the project starts, as shown below:

@SpringBootApplication
public class ApibootQuartzIntegratedAwayApplication implements CommandLineRunner {

  public static void main(String[] args) {
    SpringApplication.run(ApibootQuartzIntegratedAwayApplication.class, args);
  }

  /** * ApiBoot Quartz@link org.minbox.framework.api.boot.plugin.quartz.support.ApiBootQuartzServiceDefaultSupport}
    */
  @Autowired
  private ApiBootQuartzService quartzService;

  @Override
  public void run(String... args) throws Exception { quartzService.newJob(ApiBootOnceJobWrapper.Context() .jobClass(DemoJob.class) .wrapper()); }}Copy the code

CommandLineRunner is the logic provided by SpringBoot to execute a project after startup.

After starting the project, the console output is as follows:

. Mission carried out..Copy the code

For those of you who are concerned, I will look at what the appappingclass apiBootonceJobappappingcan do.

Type on the blackboard and underline

Quartz is an excellent distributed task scheduling framework that ApiBoot encapsulates, gives it wings, and lets us understand another layer of simple definitions.

Code sample

If you like this article please click Star for source repository, thanks!! The sample source code for this article can be obtained in the following directory: apiboot-Quartz -integrated- Away

  • Gitee:gitee.com/minbox-proj…

Author’s personal blog uses the open source framework ApiBoot to help you become an Api service architect