1. Asynchronous tasks

In Java applications, most of the interactive processing is achieved by means of synchronization. However, when dealing with the interaction with the third party system, it is easy to cause slow response, most of the previous use of multithreading to complete such tasks. In fact, since Spring 3.x, @async has been built in to solve this problem.

Use @enableaysnc and @aysnc annotations

package com.moti.task;



import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

@Service

public class AsyncService {

// Declare this method as an asynchronous method, with the @enableAsync annotation declared in SpringBootApplication

    @Async

    public void hello() {

        try {

            Thread.sleep(3000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("In processing the data...");

    }

}

Copy the code

Note: The @enableAsync annotation is declared in SpringBootApplication.

img

2. Scheduled tasks

Projects often need to perform scheduled tasks, such as analyzing logs from the previous day at dawn every day. Spring provides us with a way to perform task scheduling asynchronously, providing TaskExecutor and TaskScheduler interfaces. We only need two annotations to implement the scheduled task.

Use @enablescheduling and @scheduled annotations

package com.moti.task;



import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Service;



@Service

public class ScheduleService {

// second minute day month week

//    @Scheduled(cron = "0 * * * * Mon-FRI")

//    @Scheduled(cron = "0,1,2,3,4,5 * * * * Mon-FRI")

//    @Scheduled(cron = "0-5 * * * * Mon-FRI")

    @Scheduled(cron = "0/5 * * * * Mon-FRI") // Starts from 0 seconds and executes every 5 seconds

    public void hello() {

        System.out.println("Hello timed task!");

    }

}

Copy the code

Note: declare the @enablescheduling annotation in SpringBootApplication.

img

Cron expression details

A Cron expression is a string separated by five or six Spaces and divided into six or seven fields, each field representing a meaning. Cron has the following two syntax formats:

  1. Seconds Minutes Hours DayofMonth Month DayofWeek Year
  2. Seconds Minutes Hours DayofMonth Month DayofWeek

The SpringBoot Schedule value supports a six-field expression, which means that the year cannot be set. If more than six fields are set, an error is reported.

A, structure,

Corn from left to right (separated by Spaces) : second, minute, hour, date in a month, month, date in a week, year

Two, the meaning of each field

field permitted Special characters allowed
Seconds (Seconds) An integer 0 ~ 59 , – * / Contains four characters
Points (Minutes) An integer 0 ~ 59 , – * / Contains four characters
Hours (Hours) An integer 0 ~ 23 , – * / Contains four characters
Date (DayofMonth) Integers from 1 to 31 (but you need to consider the number of days in your month) , – *? / L W C Eight characters
Month (Month) The value is an integer ranging from 1 to 12 or jan-dec , – * / Contains four characters
Week (DayofWeek) An integer from 1 to 7 or Sun-sat (1=SUN) , – *? / L C # eight characters
Year (optional, leave blank) (Year) 1970 ~ 2099 , – * / Contains four characters

Each field uses numbers, but the following special characters can also appear, which mean:

  1. : matches any value of the field. If used in the Minutes fieldThat is, events are triggered every minute.
  2. ? : Applies only to the DayofMonth and DayofWeek domains. It also matches any value of the field, but it doesn’t. Because DayofMonth and DayofWeek affect each other. For example, if you want to trigger scheduling on the 20th of each month, you can only use the following command: 13, 13, 15, 20 *? , the last digit can only be used? If * is used to indicate that the trigger is triggered no matter what day of the week, which is not the case.
  3. – : indicates the range. For example, using 5-20 in the Minutes field triggers every minute from 5 to 20 Minutes
  4. / : Indicates that the trigger starts at the start time and is triggered at fixed intervals. For example, using 5/20 in the Minutes field means that it fires once every 5 Minutes, while 25,45, and so on fire once.
  5. , : lists enumeration values. For example, using 5,20 in the Minutes field means firing at 5 and 20 Minutes per minute.
  6. L: in the end, the value can only be in the DayofWeek and DayofMonth fields. If 5L is used in the DayofWeek field, it is triggered on the last Thursday.
  7. W: indicates a valid working day (Monday to Friday). The event can be generated only in the DayofMonth field. The system triggers an event on the latest valid working day to the specified day. For example, if 5W is used in DayofMonth, if the 5th falls on a Saturday, it will be triggered on the nearest working day: Friday, the 4th. If the 5th falls on a Sunday, the 6th (Monday) is triggered; If the 5th falls on a day between Monday and Friday, it is triggered on the 5th. Another point is that the recent search for W does not cross months.
  8. LW: The two characters can be used together to indicate the last working day of a month, i.e. the last Friday.
  9. #: used to determine the day of the month and can only appear in the DayofMonth field. For example, 4#2 is the second Wednesday of a month.

Examples of common expressions

(1) 0 0 2 1 *? * Indicates that tasks are adjusted at 2am on the first day of each month

(2) 0 15 10? * Mon-FRI indicates that the job will be executed at 10:15 a.m. each day, Monday through Friday

(3) 0 15 10? 6L 2002-2006 indicates the last Friday of each month in 2002-2006 at 10:15 am

(4) 0 0 10,14,16 * *? Every day at 10 a.m., 2 p.m., 4 p.m

(5) 0/30 9-17 * *? Every half hour during your 9-5 working hours

(6) 0 0 12? * WED means every Wednesday at 12 noon

(7) 0 0 12 * *? It's triggered every day at 12 noon

(8) 0, 15, 10? * * triggers every day at 10:15 a.m

(9) 0 15 10 * *? Triggered every day at 10:15 a.m

(10) 0 15 10 * *? * Triggered every day at 10:15 a.m

(11) 0 15 10 * *? 2005 2005 triggered every day at 10:15 a.m

(12) 0 * 14 * *? Triggered every minute between 2 p.m. and 2:59 p.m. each day

(13) 0 0/5 14 * *? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. each day

(14) 0/5 14,18 * *? Triggered every 5 minutes between 2 p.m. and 2:55 p.m. and 6 p.m. and 6:55 p.m. each day

(15) 0 0-5 14 * *? Triggered every minute between 2 p.m. and 2:05 p.m. each day

(16) 0, 10,44, 14? 3 WED triggers at 2:10 PM and 2:44 PM on Wednesdays of March each year

(17) 0, 15, 10? * Mon-FRI triggers Monday through Friday at 10:15 a.m

(18) 0, 15, 10, 15 times? Triggered at 10:15 am on the 15th of each month

(19) 0 15 10 L *? Triggered at 10:15 a.m. on the last day of each month

(20) 0, 15, 10? * 6L triggers at 10:15 am on the last Friday of every month

(21) 0, 15, 10? * 6L 2002-2005 The last Friday of each month from 2002 to 2005 was triggered at 10:15 am

(22) 0, 15, 10? * 6#3 Third Friday of each month triggered at 10:15 am

Copy the code

Note:

Some subexpressions can contain ranges or lists

For example, the subexpression (day (week)) can be “mon-fri”, “MON, WED, FRI”, “mon-wed,SAT”

The * character represents all possible values

Therefore, “” in the subexpression (month) represents the meaning of each month, and” “in the subexpression (day (week)) represents each day of the week

The slash character is used to specify the increment of a value

For example, “0/15” in the subexpression (minutes) means the beginning of the 0 minute, and “3/20” in the subexpression (minutes) means the beginning of the 3 minute, and every 20 minutes (it has the same meaning as “3, 23, 43”)

“?” The character is used only in day (month) and day (week) subexpressions, indicating that no value is specified

When one of the two subexpressions is specified, the value of the other subexpression is set to? To avoid conflicts.

The “L” character is used only in day (month) and day (week) subexpressions, and is a contraction of the word “last”

But it has a different meaning in the two subexpressions. In the day (month) subexpression, “L” indicates the last day of a month. In the day (week) self-expression, “L” indicates the last day of a week, that is, SAT

If there is something concrete before the “L”, it has other meanings

For example: “6L” means the sixth to last day of the month, “FRIL” means the last Friday of the month Note: Do not specify lists or ranges when using the “L” argument, as this can cause problems


3. Email tasks

Introduce mail task dependencies

<! -- Introducing mail task dependencies -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-mail</artifactId>

        </dependency>

Copy the code

Configure mail information in the SpringBoot configuration file

[email protected]

spring.mail.password=pxmetzjvkbgtbiji

spring.mail.host=smtp.qq.com

Copy the code

Spring.mail. password is obtained using the following method

img
img

The test code

package com.moti;



import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.mail.javamail.JavaMailSenderImpl;

import org.springframework.mail.javamail.MimeMessageHelper;



import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import java.io.File;



@SpringBootTest

class SpringBootTaskApplicationTests {

// Inject the mail sender

    @Autowired

    JavaMailSenderImpl mailSender;



/ * *

* Send a simple email

* /

    @Test

    void contextLoads() {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject("I am the title.");

        message.setText("I'm the content of the email.");

        message.setFrom("[email protected]");

        message.setTo("[email protected]");

        mailSender.send(message);

    }



/ * *

* Send complex emails

* /

    @Test

    public void test() throws MessagingException {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

// Support file upload

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject("I am the title.");

        helper.setText("

I am content, I support HTML tags oh ~

"
.true);

        helper.setFrom("[email protected]");

        helper.setTo("[email protected]");

// Upload the file

        helper.addAttachment("1.jpg",new File("E: \ \ \ \ 1. Wallpaper PNG"));

        helper.addAttachment("2.jpg",new File("E: \ \ \ \ wallpaper 2. PNG"));

        mailSender.send(mimeMessage);

    }

}

Copy the code