Spring Boot Boot Timer task

Source: Internet
Author: User

1.

Integration of timed tasks in spring boot

In the Startup class, add an annotation that opens a timed task:

The use of timed tasks in Springboot is fairly straightforward. First, we add @enablescheduling to the startup class to open the timed task.

@EnableScheduling  Public class startapplication {        publicstaticvoid  main (string[] args) {                Springapplication.run (startapplication. class , args);}    }

2. Then we directly create the service that performs the scheduled task, for example:

@Service  Public class testservice {        // per minute start    @Scheduled (cron= "0 0/1 * * *?") Publicvoid  Test () {        System.out.println ("I am Testing Schedule" )     );    }}

Operation Result:

As you can see, the method has been executed once every minute.

Next:

Let's talk about cron expressions: You can refer to this article: https://www.cnblogs.com/javahr/p/8318728.html

In addition to the way above, you can also specify fixedrate,fixeddelay,initialdelay and other ways to set the timing mode, such as:

 PackageCom.zlc.service;Importjava.util.Date;Importorg.springframework.scheduling.annotation.Scheduled;ImportOrg.springframework.stereotype.Service; @Service Public classTestservice {//start once per minute@Scheduled (cron= "0/5 * * * * *?"))     Public voidTest () {System.out.println ("I AM Testing Schedule"); }      //executes every 5 seconds after the last boot time point@Scheduled (Fixedrate= 5000)     Public voidtest1 () {System.out.println ("QD:" +NewDate ()); }        //executes every 5 seconds after the last end time point@Scheduled (Fixeddelay = 5000)     Public voidtest2 () {System.out.println ("JS:" +NewDate ()); }        //first delay x second execution, followed by fixedrate rules every x seconds@Scheduled (InitialDelay = 5000,fixedrate = 6000)     Public voidtest3 () {System.out.println ("Sdsds"); }    }

Spring Boot Boot Timer task

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.