Springboot use scheduled to do timed tasks

Source: Internet
Author: User
Tags dateformat local time

There are many open-source frameworks such as quartz, @Scheduled is a timed task annotation of spring, which can be easily and conveniently based on the annotation configuration.

First, @Scheduled notes introduction

This is the first place to put @scheduled annotations. Then the following is an introduction to these several properties.

* Copyright 2002-2018The original author or authors. Packageorg.springframework.scheduling.annotation;Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Repeatable;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/*** An annotation, marks a method to be scheduled. Exactly one of * the {@link#cron ()}, {@link#fixedDelay ()}, or {@link#fixedRate ()} * attributes must be specified. * * <p>the Annotated method must expect no arguments. It would typically have * a {@codevoid} return type; If not, the returned value is ignored * when called through the scheduler. * * <p>processing of {@code@Scheduled} annotations is performed by * registering a {@linkScheduledannotationbeanpostprocessor}. This can is * do manually or, more conveniently, through the {@code<task:annotation-driven/>} * element or @{@linkenablescheduling} annotation. * * <p>this annotation may used as a <em>meta-annotation</em> to create custom * <em>composed A Nnotations</em> with attribute overrides. * * @authorMark Fisher *@authorDave Syer *@authorChris Beams *@since3.0 *@seeenablescheduling *@seeScheduledannotationbeanpostprocessor *@seeSchedules*/@Target ({elementtype.method, elementtype.annotation_type}) @Retention (retentionpolicy.runtime) @ Documented@repeatable (schedules.class) Public@InterfaceScheduled {/*** A cron-like expression, extending the usual un*x definition to include * triggers on the second as well as  Minute, hour, day of month, month * and day of week. e.g. {@code"0 * * * * MON-FRI"} means once per minute on * Weekdays (at the top of the minute-the 0th second). * @returnAn expression so can be parsed to a cron schedule *@seeOrg.springframework.scheduling.support.CronSequenceGenerator*/String cron ()default""; /*** A time zone for which the cron expression would be resolved.     By default, this * attribute is the empty String (i.e. the server ' s local time zone would be used). * @returna zone ID accepted by {@linkJava.util.timezone#gettimezone (String)}, * or an empty String to indicate the server ' s default time zone * 
    @since4.0 *@seeOrg.springframework.scheduling.support.crontrigger#crontrigger (String, java.util.TimeZone) *@seeJava.util.TimeZone*/String Zone ()default""; /*** Execute The annotated method with a fixed period in milliseconds between the ' end of the last invocation a     nd the start of the next. * @returnThe delay in milliseconds*/    LongFixeddelay ()default-1; /*** Execute The annotated method with a fixed period in milliseconds between the ' end of the last invocation a     nd the start of the next. * @returnthe delay in milliseconds as a String value, e.g. a placeholder * or a {@linkjava.time.duration#parse Java.time.Duration} compliant value *@since3.2.2*/String fixeddelaystring ()default""; /*** Execute The annotated method with a fixed period in milliseconds between * invocations. * @returnThe period in milliseconds*/    LongFixedrate ()default-1; /*** Execute The annotated method with a fixed period in milliseconds between * invocations. * @returnthe period in milliseconds as a String value, e.g. a placeholder * or a {@linkjava.time.duration#parse Java.time.Duration} compliant value *@since3.2.2*/String fixedratestring ()default""; /*** Number of milliseconds to delay before the first execution of a * {@link#fixedRate ()} or {@link#fixedDelay ()} task. * @returnThe initial delay in milliseconds *@since3.2*/    LongInitialDelay ()default-1; /*** Number of milliseconds to delay before the first execution of a * {@link#fixedRate ()} or {@link#fixedDelay ()} task. * @returnthe initial delay in milliseconds as a String value, e.g. a placeholder * or a {@linkjava.time.duration#parse Java.time.Duration} compliant value *@since3.2.2*/String initialdelaystring ()default"";}
View Code

Cron Properties
This is a time expression that can be configured for a variety of times with a simple configuration, and we can do it almost any time with a cron expression, which contains six or seven domains:
Seconds: Can appear ",-*/" four characters, valid range is 0-59 integer
Minutes: Can appear ",-*/" four characters, valid range is 0-59 integer
Hours: Can appear ",-*/" four characters, valid range is 0-23 integer
DayOfMonth: Can appear ",-*/? L W C "Eight characters, integer with valid range 0-31
Month: Can appear ",-*/" four characters, a valid range of 1-12 integers or jan-dec
DayofWeek: Can appear ",-*/? L C # "Four characters, a valid range of 1-7 integers or Sun-sat two ranges. 1 means Sunday, 2 means Monday, and so on
Year: Can appear ",-*/" four characters, valid range is 1970-2,099 years
"0 0 12 * *?" Triggered 12 o'clock noon every day
"0 15 10?" * * "trigger 10:15 every day"
"0 15 10 * *?" Triggered 10:15 daily
"0 15 10 * *?" * "10:15 per day" trigger
"0 15 10 * *?" 2005 "2005-year daily 10:15 Trigger
"0 * 14 * *?" Daily from 2 o'clock in the afternoon to 2:59 per minute trigger
"0 0/5 14 * *?" Every 5 minutes from 2 o'clock in the afternoon to 2:55
"0 0/5 14,18 * *?" Daily from 2 o'clock in the afternoon to 2:55 and from 6 to 6:55 every 5 minutes for two time periods
"0 0-5 14 * *?" Daily 14:00 to 14:05 triggers per minute
"0 10,44 14?" 3 WED "March of 14:10 and 14:44 triggers per Wednesday
"0 15 10?" * MON-FRI "10:15 triggers per Monday, Tuesday, Wednesday, Thursday, Friday

Fixedrate Property
The delay that is called again after the start of the previous call (without waiting for the last call to complete), so there is a recurring problem, so it is not recommended, but the amount of data can be used if it is not large at the configured interval of time.

Fixeddelay Property
The effect of this property is the opposite of the above Fixedrate, which is configured to wait until the execution of the method is deferred until the time of the configuration is completed.

InitialDelay Property
This attribute is closely related to the above Fixeddelay, fixedrate, why do you say so? The effect of this property is the first execution of the delay time, only to do the delay of the setting, and do not control other logic, so with Fixeddelay or fixedrate to use.

Ii. Examples of @Scheduled annotations

 PackageCom.example.demo;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importorg.springframework.scheduling.annotation.Scheduled;Importorg.springframework.stereotype.Component; @Component Public classschedulertask {SimpleDateFormat DateFormat=NewSimpleDateFormat ("HH:mm:ss"); @Scheduled (Fixedrate= 10000)     Public voidtimerrate () {System.out.println (Dateformat.format (NewDate ())); }        //the first delay is 1 seconds to execute, and then 2 seconds after execution@Scheduled (InitialDelay = Fixeddelay = 2000)     Public voidTimerinit () {System.out.println ("Init:" +dateformat.format (NewDate ())); }    //21 points, 41 minutes, 50 seconds a day.@Scheduled (cron = "50 41 21 * *?"))     Public voidTimercron () {System.out.println ("Current time:" + Dateformat.format (NewDate ())); }}

The code uses the @scheduled property above. is to perform print log information, the Timerinit method is executed every 2 seconds, Timercron set at 21 points 41 minutes 50 seconds to execute, Timerrate is executed every 10 seconds.

Third, add @enablescheduling annotations

The above scheduled tasks can not be executed, but also need a step, you need to set the time-to-open task, this is also very simple, just add @enablescheduling annotations on the main method.

 PackageCom.example.demo;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.scheduling.annotation.EnableScheduling, @EnableScheduling @springbootapplication Public classTestApplication { Public Static voidMain (string[] args) {Springapplication.run (testapplication.class, args); }}

Springboot use scheduled to do timed 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.