In Spring + SpringMVC environment, in general, to achieve regular tasks, we have the two options, one is to use Spring's own processor timed task @Scheduled
notes, and the other is to use third-party frameworks Quartz, Spring Boot from Spring+SpringMVC, so it naturally has the timing task implementation strategies in these two Springs, and of course it also supports Quartz. In this article, we will look at the implementation of the two timing tasks in Spring Boot.
Article Directory
1. The first way: @Scheduled
Using @Scheduled
the very easy to create a Spring Boot project directly, and add the web rely on spring-boot-starter-web, to create a successful project, add @EnableScheduling
annotations, enable the scheduled tasks:
@SpringBootApplication
@EnableScheduling
public class ScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledApplication.class, args);
}
}
Next, configure the timing task:
@Service
public class HelloService {
//前面任务的结束时间和后面任务的开始时间之间间隔2s
@Scheduled(fixedDelay = 2000)
public void fixedDelay() {
System.out.println("fixedDelay>>"+new Date());
}
//两次定时任务开始的间隔时间为2s
@Scheduled(fixedRate = 2000)
public void fixedRate() {
System.out.println("fixedRate>>"+new Date());
}
@Scheduled(initialDelay = 2000,fixedDelay = 2000)
public void initialDelay() {
System.out.println("initialDelay>>>"+new Date());
}
}
(1) the first to use
@Scheduled
annotations to open a timed task.
(2)fixedDelay
Represents the time interval between task execution, specifically the time interval between the end of this task and the start of the next task.
(3)fixedRate
Represents the time interval between task executions, specifically the time interval between the start of two tasks, that is, when the second task starts, the first task may not have ended.
(4)initialDelay
Indicates the delay time for the first task start.
(5) The unit of all time is milliseconds.
Above this is a basic usage, in addition to these basic properties, @Scheduled
annotation also supports cron
expressions, the use of cron
expressions can be very rich description of the timing of the task time. The cron expression format is as follows:
[Second] [minute] [hour] [day] [month] [week] [year]
What you need to pay attention to is that the day of the month and the day of the week may conflict, so one of the two must be ?
Wildcard meaning:
(1) It
?
means that the value is not specified, that is, it is used when the value of a certain field is not concerned. It should be noted that the day of the month and the day of the week may conflict, so when configuring, one of the two must be?
(2)*
Means all values, for example: set on the second field*
, which means that every second will be triggered
(3),
Used to separate multiple values, for example, set "MON, WED, FRI" on the week field to indicate Monday, Wednesday and Friday trigger.
(4)-
Represent interval, for example, set "10-12" on the second to indicate 10 ,11,12 seconds will trigger
(5)/
for incremental triggering. For example, setting "5/15" on the second means starting from 5 seconds and triggering every 15 seconds (5,20,35,50)
(6)#
serial number ( Represents the first few weeks of the month), for example, setting "6#3" in the week field means that it is on the third Saturday of each month (it is suitable for Mother's Day and Father's Day)
(7) Week The field settings, if English letters are used, are case-insensitive, that is, MON is the same as mon
(8)L
means the final meaning. In the day field setting, it means the last day of the month (according to the current month, if it is February, it will automatically determine whether it is a lucrative year), in the week field it means Saturday, which is equivalent to "7" or "SAT" (note Sunday It is the first day). If you add a number before "L", it means the last one of the data. For example, setting the format "6L" on the week field means "the last Friday of the month"
(9)W
Indicates the nearest working day (Monday to Friday) from the specified date. For example, setting "15W" in the day field means that the trigger is triggered on the working day nearest to the 15th of each month. If the 15th happens to be a Saturday, find the nearest Friday (14th) to trigger, if the 15th is a weekday, find the nearest next Monday (16th) to trigger, if the 15th happens to be on a working day (Monday to Week 5), it will be triggered on that day. If the specified format is "1W", it means triggering on the nearest working day after the 1st of each month. If the 1st falls on Saturday, it will be triggered on the 3rd next Monday. (Note, "W" can only be set before the specific numbers are not allowed interval "-")
(10)L
andW
can be a combination. If "LW" is set in the day field, it means it will be triggered on the last working day of the month (generally referring to payroll)
In @Scheduled
to a simple cron expression annotations, trigger once every 5 seconds
@Scheduled(cron = "0/5 * * * * ?")
public void cron() {
System.out.println("cron>>"+new Date());
}
Two, the second way: Quartz
Generally in the project, unless regular tasks related to the business is so simple to use @Scheduled
annotations to solve regular tasks, or in most cases they are likely to use Quartz to do regular tasks. To use Quartz in Spring Boot, you only need to add Quartz dependencies when creating a project:
After the project is created, you also need to add a comment to start the scheduled task:
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
In the process of using Quartz, there are two key concepts, one is JobDetail (what to do) and the other is trigger (when to do it). To define JobDetail, you need to define Job first. There are two ways to define Job:
The first way is to directly define a Bean:
@Component
public class MyFirstJob {
public void sayHello() {
System.out.println("first job say hello:" + new Date());
}
}
Two points about this definition:
(1) First register this job in the Spring container.
(2) This method of definition has a flaw, that is, it cannot pass parameters.
The second definition of the way, it is inherited QuartzJobBean
and implement the default method:
public class MySecondJob extends QuartzJobBean {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("second job say hello:" + name + ":" + new Date());
}
}
Compared with the first method, this method supports parameter passing, and the executeInternal
method will be executed when the task is started .
After Job had, then create classes, configuration JobDetail
and Trigger
triggers, as follows:
@Configuration
public class QuartzConfig {
@Bean
MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {
MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
bean.setTargetBeanName("myFirstJob");
bean.setTargetMethod("sayHello");
return bean;
}
@Bean
JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean bean = new JobDetailFactoryBean();
JobDataMap map = new JobDataMap();
map.put("name", "Yolo");
bean.setJobDataMap(map);
bean.setJobClass(MySecondJob.class);
return bean;
}
@Bean
SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
bean.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());
bean.setStartTime(new Date());
bean.setRepeatInterval(2000);
bean.setRepeatCount(3);
return bean;
}
@Bean
CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
bean.setJobDetail(jobDetailFactoryBean().getObject());
bean.setCronExpression("* * * * * ?");
return bean;
}
@Bean
SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
bean.setTriggers(simpleTriggerFactoryBean().getObject(),cronTriggerFactoryBean().getObject());
return bean;
}
@Bean
HelloService helloService() {
return new HelloService();
}
}
Configuration instructions:
(1) There are two ways to configure JobDetail:
MethodInvokingJobDetailFactoryBean
andJobDetailFactoryBean
.
(2) useMethodInvokingJobDetailFactoryBean
to configure the name name and the target method of target Bean, this approach does not support mass participation.
(3) useJobDetailFactoryBean
to configureJobDetail
the task class inherits fromQuartzJobBean
, in this way to support parameter passing, encapsulated in the parameterJobDataMap
passed in.
(4)Trigger
Refers to triggers.Quartz
Multiple triggers are defined in it. Here I will show you the usage of two of them,SimpleTrigger
andCronTrigger
.
(5)SimpleTrigger
somewhat similar to the front of that@Scheduled
basic usage.
(6)CronTrigger
is somewhat similar to@Scheduled
thecron
usage of the expression.
Can be seen that SimpleTriggerFactoryBean
the control first job
interval of two seconds printing, three print
CronTriggerFactoryBean
control second job
, once every second print