The previous framework used the quartz framework to perform timing scheduling problems,
The boss said the configuration is too cumbersome, each schedule needs to be added in the spring configuration,
Can reduce the amount of configuration to improve development efficiency,
Recently looked at spring's scheduled using annotations to dispatch,
Feel very convenient, at least the configuration of things a lot less,
So stay for forgetting,
First, we need to configure our Spring.xml
xmlns add the following content,
Java code
- xmlns:task="Http://www.springframework.org/schema/task"
Then xsi:schemalocation add the following content,
Java code
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.1.xsd
And finally, our task mission scan annotations.
Java code
- <task:annotation-driven/>
My configuration scan location is:
Java code
- <context:annotation-config/>
- <bean class="Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
- <context:component-scan base-package="com.test"/>
Scan the contents of a package such as Com.test,
The following interfaces and implementations are required (my Java files are all under the Com.test package)
[Java]View Plaincopy
- Public interface Imytestservice {
- public void MyTest ();
- }
[Java]View Plaincopy
- @Component //import org.springframework.stereotype.Component;
- Public class Mytestserviceimpl implements Imytestservice {
- @Scheduled (cron="0/5 * * * *?") //Once every 5 seconds
- @Override
- public void MyTest () {
- System.out.println ("Enter Test");
- }
- }
After execution, the console will print out and enter the test.
A few things to note:
1, spring @scheduled annotations need to write on the implementation,
2, the task method of the timer can not have a return value (if there is a return value, spring initialization will tell you that there is an error, you need to set a Proxytargetclass value of true, go to Baidu Google bar)
3, the implementation of the class to have component annotations @component
The rest is corn expression, specific use and parameters please Baidu Google,
Here are just a few examples.
Cron expression meaning
"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
Perform scheduled tasks using spring @Scheduled annotations