SpringBoot timing tasks

In the project, because the third-party payment (Alipay and WeChat payment) is used, after the payment is completed, the third-party payment platform will generally use the asynchronous callback notification method to notify the merchant of the payment result, and then the merchant will change the payment order of the merchant's project according to the content of the notification. condition. Generally speaking, in order to prevent the merchant project itself due to some special reasons, such as the unstable network status at that time, the merchant callback interface cannot be accessed, or the merchant callback interface is abnormal. Third-party payment platforms generally send multiple requests to ensure that notifications are sent to the merchant system as much as possible.

However, there will always be various situations, resulting in that after all the notification times of the third-party platform have been notified, the merchant system still does not correctly process the status of the changed order. (Generally, the third-party payment platform will notify the merchant payment interface for 1 minute, 10 minutes, 1 hour, 6 hours, 12 hours, and 24 hours. Of course, this time is just an example. The actual notification time will be different from this, but also roughly). When the notification is completed at this frequency, the third-party payment platform will no longer notify.

Therefore, once the third-party payment platform has sent the number of notifications, the platform still has not processed the order status of its own project, then the order status is likely to be that the customer has actually completed the payment, but the project still displays: "Waiting for payment" "Such a state. So in order to solve this kind of problem, generally, we will use the method of timed tasks, such as 1 hour, we have paid the order for more than 1 hour, but the order has not exceeded 24 hours, and go to the third-party platform to actively check the order status once. Avoid inconsistencies in the order status caused by your own reasons. The reason why this type of setting has been more than 1 hour and not more than 24 hours is mainly for query efficiency. Because the payment has not been paid within half an hour, we believe that this possibility exists in practice, so we can wait for 1 hour to check the status. The reason why it does not exceed 24 hours is that once it exceeds 24 hours, we can think that the order has actually timed out and failed. If we check this order, it will lead to each timed task. Inquire. Causes a lot of unnecessary queries. Generally, we will also start a scheduled task, which will be executed once every 24 hours, and reset some orders to failure. Reduce unnecessary repeated queries for failed orders.

Let's get to the point, how to deal with timed tasks in spring boot.
By default, springboot already supports the Schedule module for timed tasks, so in general, it can fully meet our actual needs. Generally speaking, there is no need to add other things like: quartz

In addition, here is an actual project, about timed tasks. Some architectural considerations:

Generally speaking, in practical projects, in order to improve the responsiveness of services, we generally do it through load balancing or reverse proxying multiple nodes. In layman's terms, we generally deploy multiple instances of the project, or deploy multiple copies, with different startup ports for each instance. But the code for each instance is actually the same. If we write timed tasks in our project, we will face a problem. For example, if we deploy 3 instances, as soon as the three instances are started, all the timed tasks will be started. Then at the same time point, the timed tasks will be started. It will be executed together, that is, it will be executed 3 times, which is likely to cause errors in our business.

Generally speaking, we have several simple ways to deal with it:

1. Add custom configuration to the configuration file and control it through switches: such as adding: schedule=enable, schedule=disable, so that in our actual code, in To judge, that is, we can achieve through configuration that only one instance actually executes the scheduled task, and the other instances do not execute. However, this method actually starts the scheduled tasks, but during the execution, we manually make judgments and execute the real processing logic.
2. Logic separation means that we write the logic that we really need to process the scheduled tasks as a rest service or rpc service, and then we can create a separate scheduled task project. This project should not have any business code. It only has timing. The task function, when to start, or how often to start, after startup, through rest or RPC, the service that actually processes the logic is called. At the same time, we don't even need to create a new project, we can do it through linux cron. At the same time, this method also has an advantage. For example, sometimes, our scheduled task will have problems for some reason and it is not executed, then we can use curl or wget and many other methods to schedule the execution of the task again.

Therefore, individuals generally prefer to use the second method to achieve the separation of timed tasks and business processing.

In spring boot, how to use timed tasks is relatively simple. According to the second method, in fact, I need to create a new project to complete the function of timed tasks. In fact, we can create a new ordinary java project and introduce quartz to achieve it, but here, I do it through spring boot. A spring boot project, the initialization of the project can be used: http://start.spring.io After

initialization, we are allowed to support schedule in the entry class Application.java of spring boot

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

Then, create a new execution class Jobs.java

@Component
public class Jobs {
    public final static long ONE_Minute =  60 * 1000;

    @Scheduled(fixedDelay=ONE_Minute)
    public void fixedDelayJob(){
        System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>fixedDelay执行....");
    }

    @Scheduled(fixedRate=ONE_Minute)
    public void fixedRateJob(){
        System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>fixedRate执行....");
    }

    @Scheduled(cron="0 15 3 * * ?")
    public void cronJob(){
        System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>cron执行....");
    }
}

These are the simplest two ways, how many minutes to execute once, fixedDelay and fixedRate, the unit is milliseconds, so 1 minute is 60 seconds × 1000
The difference between them is that fixedRate is once every many minutes, no matter how much your business execution costs. time. I execute it once a minute, and fixedDelay is executed 1 minute after the task is executed. So according to the actual business, we will choose different ways.

There is also a type of timed task, such as execution at 3:15 every day, then we need to use another method: cron expression

cron expression, which has a special syntax, and it feels a bit confusing, but in short, You can remember some common usages, and special grammars can be checked separately.
cron has a total of 7 digits, but the last digit is the year, which can be left blank, so we can write 6 digits:

* the first digit, representing seconds, has a value of 0-59
* the second digit, representing minutes, has a value of 0-59
* The third digit, indicating the hour, the value is 0-23
* The fourth digit, the date day/day, the value is 1-31
* The fifth digit, the date month, the value is 1-12
* The sixth digit, the day of the week, the value 1-7, Monday, Tuesday..., Note: not the first week, the meaning of the second week
          : 1 means Sunday, 2 means Monday.
* The 7th is the year, which can be left blank. The value is 1970-2099. In
cron, there are some special symbols with the following meanings:

(*) Asterisk: can be understood as the meaning of every, every second, every minute, every day, Monthly, yearly...
(?) Question mark: The question mark can only appear in the two positions of the date and the week, indicating that the value of this position is uncertain, and it is executed at 3 o'clock every day, so we do not need to pay attention to the position of the sixth week, it is uncertain value. Also: date and week are two mutually exclusive elements, indicated by a question mark to indicate no value is specified. For example, January 10, for example, is Monday 1. If the position of the week is another Tuesday, it is inconsistent.
(-) minus sign: express a range, such as using "10-12" in the hour field, it means from 10 to 12 o'clock, that is, 10,11,12
(,) comma: express a list value, such as in the week field If "1,2,4" is used in , it means Monday, Tuesday, Thursday
(/) slashes: such as: x/y, x is the starting value, y is the step size, such as in the first place (seconds) 0/ 15 is, starting from 0 seconds, every 15 seconds, and finally 0, 15, 30, 45, 60 Another: */y, equivalent to 0/y
Here are a few examples for everyone to verify:

0 0 3 * * ? Execute
0 5 3 * * every day at 3:00? Execute
0 5 3 every day at 3:5? * * Execute at 3:5 every day, same as above
0 5/10 3 * * ? 5 minutes at 3:00 every day, 15 minutes , 25 minutes, 35 minutes, 45 minutes, 55 minutes these time points to execute
0 10 3 ? * 1 Every Sunday, 3:10 to execute, Note: 1 means Sunday   
0 10 3 ? * 1#3 every month In the third week of the week, it will be executed on Sunday. The # sign can only appear in the position of the week.






© Statement: Unless otherwise specified, all articles on this site are original. Please indicate the address of this article in the form of a link for reprinting.
©Reprint please indicate the source: https://www.rkf.cn/springboot-schedule-cron/

Author: Tao Qingqing
Link : http://www.jianshu.com/p/efk8af5a8c1d
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326334246&siteId=291194637