Springboot (9)---timed tasks, asynchronous tasks

Source: Internet
Author: User

Timed tasks, asynchronous tasks

I. Scheduled Tasks

1. Steps:

1: Write @EnableScheduling annotations on the startup class

2: Write @component on the class for which you want to schedule tasks

3: Write @Scheduled(fixedrate= milliseconds) on the method to be executed on a timed basis.

2. Example

Main class

@SpringBootApplication@EnableScheduling  // turn on timed tasks  Public class mainapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (mainapplication. class , args);}    }

Timed Task Class

Importjava.util.Date;Importorg.springframework.scheduling.annotation.Scheduled;Importorg.springframework.stereotype.Component; @Component  Public classJobs {//represents 5 seconds after method execution completes    @Scheduled(fixeddelay=5000)     Public voidFixeddelayjob ()throwsinterruptedexception{System.out.println ("Fixeddelay every 5 Seconds" +NewDate ()); }        //indicates every 3 seconds   @Scheduled(fixedrate=3000)     Public voidFixedratejob () {System.out.println ("Fixedrate every 3 seconds" +NewDate ()); }    //represents 0 seconds per day 3:15   @Scheduled(cron= "0 15 3 * *?"))     Public voidcronjob () {System.out.println (NewDate () + "... >>cron ..."); }}

Effect:

3. Summary

1.fixeddelay and fixedrate, units are milliseconds, here is 5 seconds and 3 seconds, the difference is :

,fixedrate is once every few minutes, no matter how much time you spend doing business. I was executed 1 times in 1 minutes, and Fixeddelay was executed 1 minutes after the task was executed. So depending on the actual business, we will choose different ways.

2.cron expression: For example, if you want to set the time to execute every day, you can use it

Cron expressions, have a special syntax, and feel a bit around people, but in simple terms, we remember some common usage, special grammar can be checked separately.
Cron has a total of 7, but the last one is years and can be left blank, so we can write 6 bits:

* First digit, indicating seconds, value 0-59 * Second digit, the value of 0-59* third, the hour, the value 0-23* fourth, Date day/day, the value 1-31* fifth, date and month, value 1-12* sixth, week, value 1-7, Monday, Tuesday ..., note: Not 1th week, the second week of the meaning          In addition: 1 represents Sunday, 2 represents Monday. * 7th for, year, can be left blank, value 1970-2099

Cron, there are some special symbols, meaning the following:

(*) Asterisk: Can be understood as each meaning, per second, per minute, daily, monthly, yearly ... (?) Question mark: The question mark can only appear in both the date and the week locations. (-) minus sign: Expresses a range, such as using "10-12" in the hour field, that is, from 10 to 12 points, that is, 10,11,12 (,) Comma: Expresses a list value, such as using "1,2,4" in the day of the week field, that is, Monday, Tuesday, Thursday (/) Slash: X/y, X is the start value, Y is the step, for example in the first bit (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 you to verify:

0 0 3 * * ?     3-point execution per day  5 3 * * ?    performed 3:5 daily  5 3? * *      daily 3:5, same as above 5/10 3 * * ?  3 points per day, 5 points, 15 points, 25 points, 35 points, 45 points, 55 points these hours are executed.  10 3? * 1      weekly Sunday, 3:10 execution, note: 1 means Sunday     3? * 1#3 The  third week of each month, Sunday execution, # The number can only appear in the week's position

Ii. Asynchronous Tasks

1. Steps

1: Start-up class with @EnableAsync annotation Open function, automatic scanning

2: Write @component on the class that wants the asynchronous task

3: In the definition of the asynchronous task class write @Async(written on the class to represent the entire class is asynchronous, in the method plus on behalf of the class asynchronous execution)

2. Example

Main class

@SpringBootApplication@EnableAsync   // Open Async Task Publicclass  mainapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (mainapplication. class , args);}    }

Asynchronous Classes

Importjava.util.concurrent.Future;ImportOrg.springframework.scheduling.annotation.Async;ImportOrg.springframework.scheduling.annotation.AsyncResult;Importorg.springframework.stereotype.Component;/*** Function Description: Asynchronous task Business Class*/ @Component@Async  Public classAsynctask {//Get asynchronous Results     Public  Future<String> Task4 ()throwsinterruptedexception{LongBegin =System.currenttimemillis (); Thread.Sleep (2000L); LongEnd =System.currenttimemillis (); System.out.println ("Task 4 time consuming =" + (end-begin)); return New AsyncResult<String> ("Task 4"); }             PublicFuture<string> Task5 ()throwsinterruptedexception{LongBegin =System.currenttimemillis (); Thread.Sleep (3000L); LongEnd =System.currenttimemillis (); System.out.println ("Task 5 time consuming =" + (end-begin)); return NewAsyncresult<string> ("Task 5"); }         PublicFuture<string> Task6 ()throwsinterruptedexception{LongBegin =System.currenttimemillis (); Thread.Sleep (1000L); LongEnd =System.currenttimemillis (); System.out.println ("Task 6 time consuming =" + (end-begin)); return NewAsyncresult<string> ("Task 6"); }        }

Controller class

Importjava.util.concurrent.Future;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.GetMapping;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportCom.jincou.task.AsyncTask;ImportCom.jincou.util.JsonData, @RestController @requestmapping ("/api/v1") Public classUsercontroller {@AutowiredPrivateasynctask task; @GetMapping ("Async_task")     PublicJsondata Exetask ()throwsinterruptedexception{LongBegin =System.currenttimemillis (); Future<String> TASK4 =Task.task4 (); Future<String> TASK5 =task.task5 (); Future<String> TASK6 =task.task6 (); //If all is done, you can jump out of the loop, Isdone method if this task is completed, true         for(;;) {            if(Task4.isdone () && task5.isdone () &&Task6.isdone ()) {                 Break; }        }                        LongEnd =System.currenttimemillis (); LongTotal = end-begin; System.out.println ("Total time to execute =" +Total ); returnjsondata.buildsuccess (total); }    }

Results:

Page:

Background:

3. Summary

From the example above we can see: If the synchronization method, then we need 6 seconds, and asynchronous execution, we only need about 3 seconds, this is the role of async.

1) to encapsulate the asynchronous task into a class, you cannot write directly to the controller
2) Add future<string> return result asyncresult<string>("Task execution complete");
3) If you need to get the results you need to judge all Task.isdone ()

think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Captain "10"

Springboot (9)---timed tasks, asynchronous tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.