13. Springboot Integrated timing task (scheduling tasks)

Source: Internet
Author: User

Scheduled task (scheduling tasks)

Creating a timed task in Springboot is simple and takes only 2 steps:

    • 1. Add @enablescheduling annotations at the entrance of the program.
    • 2. Add @scheduled annotations to the timing method.
1, springboot By default has helped us achieve a scheduled task, only need to add the corresponding annotations can be implementedspring-boot-starter2. Startup class Enable timing

Add annotations to the main class of spring boot @EnableScheduling to enable configuration of timed tasks

@SpringBootApplication @enablediscoveryclient@enablescheduling  Public class memberapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (memberapplication. class , args);}    }
3. Create a timed Task implementation class

Create a timed task that prints the current time in the console every 5s.

@Component Public classScheduledtasks {Private Static FinalLogger log = Loggerfactory.getlogger (scheduledtasks.class); Private Static FinalSimpleDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss"); @Scheduled (Fixedrate= 5000)     Public voidReportcurrenttime () {Log.info ("The time is now {}", Dateformat.format (NewDate ())); }}
4. Parameter description

  @Scheduled Explanation

By adding @scheduled annotations to the method, it shows that the method is a dispatch task.

    @ScheduledParameters can accept two timing settings, one that we commonly use cron="*/6 * * * * ?" , one of which is fixedRate = 6000 that both represent the printing of content every six seconds

@Scheduled (fixedrate =@scheduled): 5 Seconds after the last execution point (InitialDelay=1000, fixedrate=5000 ): Executes after the first delay of 1 seconds, followed by fixedrate rules every 5 seconds (cron= "*/5 * * * * *"): Define rules by cron expressions

Reference: Scheduling Tasks

13. Springboot Integrated timing task (scheduling 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.