Two implementations Spring Boot2 series of tutorials (xvi) the timing of the task

In Spring + SpringMVC environment, in general, to achieve regular tasks, we have the two options, one is to use Spring's own timed task processor @Scheduled notes, and the other is to use third-party frameworks Quartz, Spring Boot from Spring + SpringMVC, therefore naturally have timed task both in Spring implementation strategy, of course, also supports Quartz, Boot this article we will look at two ways of implementing timed tasks under Spring.

@Scheduled

Use @Scheduled very easy to create a Spring Boot project directly, and add the web dependent spring-boot-starter-web, the project is successfully created, add @EnableSchedulingannotations, enable the scheduled tasks:

@SpringBootApplication
@EnableScheduling
public class ScheduledApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledApplication.class, args);
    }
}

The next regular configuration tasks:

    @Scheduled(fixedRate = 2000)
    public void fixedRate() {
        System.out.println("fixedRate>>>"+new Date());    
    }
    @Scheduled(fixedDelay = 2000)
    public void fixedDelay() {
        System.out.println("fixedDelay>>>"+new Date());
    }
    @Scheduled(initialDelay = 2000,fixedDelay = 2000)
    public void initialDelay() {
        System.out.println("initialDelay>>>"+new Date());
    }
  1. The first to use @Scheduled comment open a timed task.
  2. fixedRate represents the time interval between task execution, specifically refers to the start time interval two missions that began when the second task, the first task may not over yet.
  3. fixedDelay represents the time interval between task execution, specifically refers to the end of this task to the time interval between the start of the next task.
  4. initialDelay represents a delay time for the first time the task started.
  5. All units of time are milliseconds.

Above this is a basic usage, in addition to these basic properties, @ Scheduled annotation also supports cron expressions, use cron expression, can be very rich description of the timing of the task time. cron expression format is as follows:

[S] [minutes] [h] [day] [month] [weeks] [years]

Specific values ​​are as follows:

No. Explanation Required Which allowed the value of Allow wildcard
1 second Yes 0-59 - * /
2 Minute Yes 0-59 - * /
3 Time Yes 0-23 - * /
4 day Yes 1-31 - * ? / L W
5 month Yes 1-12 or JAN-DEC - * /
6 week Yes 1-7 or SUN-SAT - * ? / L ##
7 year no 1970-2099 - * /

This is one we should all be noted that the date and day of the month may be in conflict, so when these two must have a configuration is ?

Wildcard Meaning:

  • ?He said they did not specify a value that does not care when using the value of a field. It should be noted that the date and day of the month may be in conflict, so when these two must have a configuration is?
  • *It indicates all values, for example: a field provided in a second *, every second triggers represents
  • , Used to separate multiple values, such as setting "MON, WED, FRI" in the week field said on Monday, Wednesday and Friday trigger
  • - Representing the interval, for example on the second "10-12", said the 10, 11 seconds will trigger
  • / For incrementing the trigger, as provided above the second "5/15" indicates 5 seconds, every 15 seconds by a trigger (5,20,35,50)
  • ## Number (of every month the first few days of the week), for example on the field Week "6 3 ##" represents the third Saturday of each month, (with Mother's Day and Father's Day a perfect fit)
  • Set circumferential field, the use of letters is not case sensitive, i.e. the same as MON mon
  • LIt indicates that the last meaning. On the field, set the day, represents the last day (based on the current month, if February will automatically determine whether it is a leap year), for Saturday, the equivalent of "7" or "SAT" in the week field (note Sunday of the month be the first day). If the "L" digitally before, indicates the last of the data. For example, setting this format "6L" in the week field, it means "the last Friday of the month."
  • WIt represents the weekday closest to the specified date (Monday to Friday), for example, set the "15W" on the daily field representing the 15th of each month from recent days that trigger. If the 15th happens to be Saturday, you find the nearest Friday (14) is triggered, if the number 15 is the weekend, then look for the nearest next Monday (16) is triggered, if just 15 working days (Monday to Sunday e), then triggered in the day. If you specify the format of "1W", it said 1 month later recent days triggered. If Saturday is the No. 1, No. 3 will be triggered Monday. (Note, "W" can only be set before the specific numbers are not allowed interval "-")
  • LAnd Wit may be a combination. If set to "LW" in the Japanese field, then the trigger (generally refers to wages) on the last working day of the month

For example, the annotation in a simple @Scheduled cron expression, once every 5 seconds to trigger, as follows:

@Scheduled(cron = "0/5 * * * * *")
public void cron() {
    System.out.println(new Date());
}

It described above is annotated using @Scheduled way to achieve the scheduled task, let's look at how to use Quartz to achieve timing tasks.

Quartz

Generally in the project, unless regular tasks related to the business is too simple, @Scheduled annotations to solve regular tasks, or in most cases are likely to use Quartz to do regular tasks. Quartz in the Spring Boot in use, only when you create a project, add Quartz can rely on:

After the project is created, it needs to add annotations enable the scheduled tasks:

@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
    public static void main(String[] args) {
        SpringApplication.run(QuartzApplication.class, args);
    }
}

Quartz in use, there are two key concepts, one is JobDetail (to do), and the other is the trigger (when to do), to define JobDetail, need to define the definition of Job, Job in two ways:

The first way, directly define a Bean:

@Component
public class MyJob1 {
    public void sayHello() {
        System.out.println("MyJob1>>>"+new Date());
    }
}

About This definition says two things:

  1. First of all this Job registered to Spring container.
  2. This definition has a flaw, just can not pass parameters.

The second definition of the way, it is inherited QuartzJobBean and implement the default method:

public class MyJob2 extends QuartzJobBean {
    HelloService helloService;
    public HelloService getHelloService() {
        return helloService;
    }
    public void setHelloService(HelloService helloService) {
        this.helloService = helloService;
    }
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        helloService.sayHello();
    }
}
public class HelloService {
    public void sayHello() {
        System.out.println("hello service >>>"+new Date());
    }
}

And compared to the first ways, this approach to support mass participation, when the task is started, executeInternal method will be executed.

After Job had, then create a class, configure JobDetail and Trigger trigger, as follows:

@Configuration
public class QuartzConfig {
    @Bean
    MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myJob1");
        bean.setTargetMethod("sayHello");
        return bean;
    }
    @Bean
    JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MyJob2.class);
        JobDataMap map = new JobDataMap();
        map.put("helloService", helloService());
        bean.setJobDataMap(map);
        return bean;
    }
    @Bean
    SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
        SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
        bean.setStartTime(new Date());
        bean.setRepeatCount(5);
        bean.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());
        bean.setRepeatInterval(3000);
        return bean;
    }
    @Bean
    CronTriggerFactoryBean cronTrigger() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setCronExpression("0/10 * * * * ?");
        bean.setJobDetail(jobDetailFactoryBean().getObject());
        return bean;
    }
    @Bean
    SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setTriggers(cronTrigger().getObject(), simpleTriggerFactoryBean().getObject());
        return bean;
    }
    @Bean
    HelloService helloService() {
        return new HelloService();
    }
}

About this configuration, said the following:

  1. JobDetail configured in two ways: MethodInvokingJobDetailFactoryBean and JobDetailFactoryBean.
  2. MethodInvokingJobDetailFactoryBean can be configured using the target name and the name of the target Bean method, this approach does not support mass participation.
  3. 使用 JobDetailFactoryBean 可以配置 JobDetail ,任务类继承自 QuartzJobBean ,这种方式支持传参,将参数封装在 JobDataMap 中进行传递。
  4. Trigger 是指触发器,Quartz 中定义了多个触发器,这里向大家展示其中两种的用法,SimpleTrigger 和 CronTrigger 。
  5. SimpleTrigger 有点类似于前面说的 @Scheduled 的基本用法。
  6. CronTrigger 则有点类似于 @Scheduled 中 cron 表达式的用法。

全部定义完成后,启动 Spring Boot 项目就可以看到定时任务的执行了。

总结

这里主要向大家展示了 Spring Boot 中整合两种定时任务的方法,整合成功之后,剩下的用法基本上就和在 SSM 中使用一致了,不再赘述。本文案例我已经上传到 GitHub ,欢迎大家 star:https://github.com/lenve/javaboy-code-samples

关注公众号【江南一点雨】,专注于 Spring Boot+微服务以及前后端分离等全栈技术,定期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!

发布了552 篇原创文章 · 获赞 6097 · 访问量 437万+

Guess you like

Origin blog.csdn.net/u012702547/article/details/102748267