“This is the 15th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

Look at Spring Boot 2.x actuator monitoring/health check/audit/statistics

Based on the above code changes

Source: github.com/langyastudi…

Spring-fram /spring-fram…

It is often necessary to perform scheduled tasks in many applications. For example, sending reports to users every day and periodically checking system status. In the Spring + SpringMVC environment, there are generally two solutions to implement scheduled tasks:

  • One is to use the @Scheduled annotation that comes with Spring’s Scheduled task handler
  • Another is to use third-party frameworks such as Quartz

Spring comes with a solution

Spring has built-in support for scheduled tasks and Cron tasks, so you don’t need to write a lot of code by hand. Just use two annotations:

  • Enable support for scheduled tasks via @enablescheduling (based on class annotations)

  • Tasks that need to be planned using @Scheduled annotations (based on function annotations)

Scheduled

Specific steps:

Added @enablescheduling support for starting scheduled tasks:

@SpringBootApplication
@EnableScheduling
public class Application
{
    public static void main(String[] args)
    {... }}Copy the code

Next define the class for the Scheduled task (tag @Component) and annotate the Scheduled task with @Scheduled:

@Log4j2
@Component
public class SchedulingService
{
    @Scheduled(fixedRate = 60000)
    public void  fixedRateSchedule(a)
    {
        log.info("Execute fixedRateSchedule every 60 seconds...");
    }


    /** * initialDelay The task starts after five seconds */
    @Scheduled(initialDelay = 5000, fixedDelay = 10000)
    public void  fixedDelaySchedule(a)
    {
        log.info("Execute fixedDelaySchedule 10 seconds after the last task completed..."); }}Copy the code

Key parameters:

  • fixedRate

    Perform the task at regular intervals, regardless of whether the last task was completed

  • fixedDelay

    Execute a new task at a specified time after the last task has completed

  • initialDelay

    Indicates the delay for starting the first task

  • All times are in milliseconds

For example, the fixedDelaySchedule function annotation above specifies a start delay of 5 seconds and a task execution interval of 10 seconds. You can see the logs printed by the scheduled task in the console:

The 2021-08-16 18:30:14. 729 INFO [scheduling - 1] com.langyastudio.springboot.com mon. Middleware. Task. SchedulingService: Execute fixedDelay 10 seconds after the last task completed... The 2021-08-16 18:30:24. 730 INFO [scheduling - 1] com.langyastudio.springboot.com mon. Middleware. Task. SchedulingService: Execute fixedDelay 10 seconds after the last task completed... The 2021-08-16 18:30:34. 732 INFO [scheduling - 1] com.langyastudio.springboot.com mon. Middleware. Task. SchedulingService: Execute fixedDelay 10 seconds after the last task completed...Copy the code

Dynamic change parameter values:

For example, if fixedDelay=10000, what if you want to change it to 60 seconds, do you have to recompile?

You can see that the Scheduled annotation has been applied provides fixedDelayString, fixedRateString, and initialDelayString parameters. You can put the Scheduled task configuration value in the configuration file to dynamically change the Scheduled task time.

For example, to define a configuration file:

langyastudio:
  task:
    fixedDelaySchedule: 60000
Copy the code

The purpose of dynamically modifying parameter values is realized by substituting xxxString for XXX:

@Scheduled(initialDelay = 5000, fixedDelayString = "${langyastudio.task.fixedDelaySchedule:10000}")
public void  fixedDelaySchedule(a)
{
    log.info("Execute fixedDelay 10 seconds after the last task completed...");
}
Copy the code

The fixedDelayString, said langyastudio was obtained from the configuration file. The first task. FixedDelaySchedule value, if not then use the default value of 10000.

Scheduled Task configuration:

The following is an example:

spring:
  task:
    scheduling:
      pool:
        size: 5        
      shutdown:
        Whether to wait for the task to complete when closing the application
        await-termination: true
        await-termination-period: 60000 
Copy the code

With configuration parameters, you can customize the actions that a scheduled task takes when an application is closed, such as await-termination, which means to wait until completion before closing.

Cron

Cron is derived from the Unix/Linux crond daemon process and has a concise expression that defines when a task is triggered (by time, as opposed to repeated scheduled tasks).

A recommended online Cron expression generator is crontab.guru/

In Spring, you can use Cron expressions to execute Cron tasks in the following format:

┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ the second (0-59) │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ minute (0-59) │ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ the adrenaline-charged (0-23) │ │ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ day Of the month (1-31) │ │ │ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ the month (1-12) (or JAN - DEC) │ │ │ │ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ day of the week (0 7) │ │ │ │ │ │ (0 or 7 is Sunday, or MON - SUN) │ │ │ │ │ │ * * * * * * s points in hour days in weekCopy the code

The values are as follows:

The serial number instructions If required Allowed value Allowed wildcard characters
1 seconds is 0-59 – * /
2 points is 0-59 – * /
3 when is 0-23 – * /
4 day is 1-31 – *? / L W
5 month is 1-12 or JAN-DEC – * /
6 weeks is 1-7 or SUN-SAT – *? / L #
7 years no 1970-2099. – * /

Example:

Cron expression executed at 12:00 Monday through Friday:

0 0 12 * * MON-FRI
Copy the code

Cron expression executed at 12:00 on 1st – 3rd and 10th of each month:

0 0 12 1-3,10 * *
Copy the code

Define a task to execute every 30 seconds in Spring:

@Scheduled(cron = "*/30 * * * * *")
public void  cronchedule(a)
{
    log.info("Cron every 30 seconds...");
}
Copy the code

Perform the preceding tasks at xx: XX :00 or XX :xx:30

Cron can also use configuration files, which I will not detail

Quartz

Using scheduled and Cron tasks in Spring is fairly straightforward, but note that the scheduling of these tasks is within each JVM process. If you start two processes on the local machine or an application on multiple machines, the scheduled and Cron tasks of these processes run independently of each other.

If some scheduled tasks need to be run in a cluster, for example, a check task needs to be executed at 23:00 every day, only one of the tasks in the cluster needs to be run. In this case, you can use Quartz.

Quartz can be configured with a JDBC data source to store all the task scheduling plans as well as the task execution status. For more information on Quartz’s integration, refer to Spring’s documentation.