About the two ways to add timers to Springboot __java

Source: Internet
Author: User

First, build a springboot project that can be used with Maven or Gradle or other (md not ...). Because this time the focus is on how to add the timer, I will be in these days when there is time to write a how to build a simple springboot project process. Time is limited now, so. I also ask you to forgive me.

Cough. Okay, get into the subject.

Method One: Use the springboot to open the timer with its own entrance.

First we all know that Springboot has a portal of its own, namely @springbootapplication (he is a combination of annotations by @configuration,@ Enableautoconfiguration and @componentscan composition, OK well ... Pulled away).

First the timer needs to have a total switch, because I may have to schedule a lot of functions, if I want all of the temporary close can not be a note to delete it. So we need to open the total switch first, that is, add @enablescheduling this annotation at the entrance of Springboot. Code on (this is the entrance to the Springboot)

@SpringBootApplication
@EnableScheduling Public
class DemoApplication {public

	static void Main (string[] args) {
		springapplication.run (demoapplication.class, args);
	}
}
After the total switch is added, we only need to configure the timing method, using the note @scheduled (cron = "0/2 * * * * *") followed by the cron expression. Represents one execution every 2 seconds. The specific syntax of cron I will post in the end.

    @Scheduled (cron = "0/2 * * * * *") public
    Void Timer () {
        //Get current time
        LocalDateTime LocalDateTime =LOCALDATETIME.N ow ();
        System.out.println ("Current time is:" + Localdatetime.format (Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"));
    }
All right, that's it. You will find that this method is run once every two seconds (LocalDateTime is the new feature of java1.8, more clear and useful than the previous date, recommend interested students can learn, start quickly).

The current time is: 2017-05-27 15:03:42
The current time is: 2017-05-27 15:03:44
The current time is: 2017-05-27 15:03:46

Method Two: Some students may say, springboot I do not like to add a pile of mess, I will look clear, concise. Jolly. OK, students who have experience based on XML development should know. Using the timer I just do the configuration in XML to run the method I want to run according to the events I configure, yes. But Springboot claims no XML, but we can use annotations to make classes XML and code on.

@Configuration          //proof that this class is a profile
@EnableScheduling       //Open Quartz timer Total switch public
class Timer {
}
OK, that's it.  (No more.) Right. It's as simple as that. This practice and will @enablescheduling this annotation written in the springboot entrance effect is the same, two write one can. The next step is to configure the method you want to schedule.

Also give everyone mark a tip. If you generally forget the name of the key in an annotation. Not necessarily want to rush to Baidu. You can hold down the CTRL key and take a look inside the method name, for example, I forgot how to spell the cron in @scheduled. I can check in.

@Target ({elementtype.method, elementtype.annotation_type})
@Retention (retentionpolicy.runtime)
@ Documented
@Repeatable (schedules.class) public
@interface scheduled {
    String cron () default "";

    String zone () default "";

    Long Fixeddelay () default-1l;

    String fixeddelaystring () Default "";

    Long fixedrate () default-1l;

    String fixedratestring () Default "";

    Long InitialDelay () default-1l;

    String initialdelaystring () Default "";
}

will soon be able to find the corresponding spelling, do not need to go to Baidu, in case there is no net it is not.

Okay, the last cron expression is as follows (Baidu = = Don't spray)

Asterisk (*): Used in all fields to represent every moment of the corresponding time field, for example, * "Per minute" in the minute field;

Question mark (?): The character is used only in the date and week fields, which is usually specified as "meaningless value", equivalent to a bit character;

Minus sign (-): expresses a range, such as using "10-12" in the hour field, representing 10 to 12 points, i.e. 10,11,12;

Comma (,): Expresses a list value, such as "Mon,wed,fri" in the Week field, for Monday, Wednesday, and Friday;

Slash (/): X/y expresses a sequence of equal steps, X is the starting value, and Y is the increment step value. If you use 0/15 in the minute field, it is 0,15,30 and 45 seconds, and 5/15 represents 5,20,35,50 in the minute field, you can also use */y, which is equivalent to 0/y;

L: This character is used only in the date and week fields, meaning "last", but it means different in two fields. L In the Date field, represents the last day of the month, such as number 31st in January, not leap year February 28th; if L is used in the week, it means Saturday, equivalent to 7. However, if L appears in the Week field and has a value x in front of it, it means "last x days of the Month", for example, 6L represents the last Friday of the month;

W: This character can only appear in the Date field and is a cosmetic of the leading date that represents the most recent weekday from that date. For example, 15W represents the most recent working day from 15th, if the month 15th is Saturday, match 14th Friday; if 15th is Sunday, match 16th Monday; if 15th is Tuesday, the result is 15th Tuesday. But it must be noted that the associated matching date is not able to span the month, as you specify 1W, if number 1th is Saturday, the result matches the number 3rd Monday, not last month. The W string can only specify a single date and cannot specify a date range;

LW combination: In the Date field can be combined to use LW, which means the last working day of the month;

Pound sign (#): This character can only be used in the week field, indicating a weekday of the month. If 6#3 said that the third Friday of the month (6 for Friday, #3表示当前的第三个), and 4#5 that the month of the fifth Wednesday, assuming that the month does not have the fifth Wednesday, ignoring the trigger;

C: This character is used only in the date and week fields and represents the meaning of calendar. It means the date that the plan is associated with, and if the date is not associated, it is equivalent to all the dates in the calendar. For example 5C in the Date field corresponds to the first day of the calendar after 5th. 1C is equivalent to the first day after Sunday in the Week field.

Cron expressions are not sensitive to the case of special characters, nor are they sensitive to the abbreviated English case of the representative week. Table 2 shows some examples of the complete cron representation:
The meaning of cron expressions
"0 0 12 * *?" Every day at 12 o'clock noon trigger
"0 15 10?" * * "Every 10:15 trigger
"0 15 10 * *?" Triggers 10:15 every day.
"0 15 10 * *? * "Every 10:15 trigger
"0 15 10 * *? 2005 "2005 Every day 10:15 triggers
"0 * 14 * *?" Every day starting from 2 o'clock in the afternoon to 2:59 every minute of the trigger
"0 0/5 14 * *?" Every day from 2 o'clock in the afternoon to 2:55 to the end of every 5-minute trigger
"0 0/5 14,18 * *?" Triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 and 6 to 6:55
"0 0-5 14 * *?" Triggers every day from 14:00 to 14:05 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



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.