Spring timed Task @scheduled

Source: Internet
Author: User

1. Configuration files

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:task= "Http://www.springframework.org/schema/task"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.1.xsd Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/ Spring-task.xsd "Default-autowire= "ByName"Default-lazy-init= "false">    <!--Scheduled Task related configuration -    <Task:executorID= "Executor"pool-size= "Ten"queue-capacity= " +"/>    <Task:schedulerID= "Scheduler"pool-size= "Ten"/>    <Task:annotation-drivenExecutor= "Executor"Scheduler= "Scheduler"Proxy-target-class= "true"/></Beans>

2. Call

There are two ways of using

1) If you need to perform at a fixed rate, as long as you change the name of the property specified in the annotation to Fixedrate, the following method calls the execution at a fixed rate of 5s, which is the baseline of the above task start time, and is called again after the previous task begins execution 5s:

@Scheduled (Fixeddelay =)    publicvoid  testtask () {        logger.info (" Test timed Task ");    

2) using cron expressions, you can implement timed calls such as: Early morning calls, detailed cron related parameters see the following introduction

@Scheduled (cron = "cron =" 0 0 2 * *? ") )    publicvoid  testtaskwithdate () {        logger.info ("Test 2016. Scheduled Tasks" );    }

3, cron related parameter significance

A cron expression has at least 6 (or possibly 7) time elements that have a space separation.

In order of
    • Seconds (0~59)
    • Minutes (0~59)
    • Hours (0~23)
    • Days (months) (0~31, but you need to consider the number of days of your month)
    • Month (0~11)
    • Days (weeks) (1~7 1=sun or Sun,mon,tue,wed,thu,fri,sat)
    • Year (1970-2099)--@Scheduled is not supported, Spring quartz support

Each of these elements can be a value (such as 6), a continuous interval (9-12), a time interval (8-18/4) (/= every 4 hours), a list (1,3,5), and a wildcard character. Because the "date in the month" and "date in the week" are mutually exclusive, one of the two elements must be set.

0 0 10,14,16 * *? 10 o'clock in the morning, 2 o'clock in the afternoon, 4 O ' Day
0 0/30 9-17 * *? Every half hour for nine to five working hours
0 0 12? * WED means every Wednesday noon 12 o'clock
"0 0 12 * *?" trigger 12 o'clock noon every day.
"0 15 10?" * * "trigger 10:15 every day"
"0 15 10 * *?" Daily 10:15 Trigger
"0 15 10 * *?" * "10:15 per day" trigger
"0 15 10 * *?" 2005 "2005-year daily 10:15 Trigger
"0 * 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:59 daily
"0 0/5 14 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily
"0 0/5 14,18 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily and from 6 o'clock in the afternoon to 6:55
"0 0-5 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:05 daily
"0 10,44 14?" 3 WED "2:10 and 2:44 triggers in Wednesday of every March
"0 15 10?" * Mon-fri "Monday to Friday 10:15 trigger
"0 15 10 15 *?" 15th 10:15 per month
"0 L *?" 10:15 on the last day of the month
"0 15 10?" * 6L "Last month of Friday 10:15 Trigger
"0 15 10?" * 6L 2002-2005 "2002 to 2005 the last of the monthly Friday 10:15 trigger
"0 15 10?" * 6#3 "Monthly third Friday 10:15 trigger

Some sub-expressions can contain ranges or lists

For example: subexpression ( Day (week)) can be "Mon-fri", "Mon,wed,fri", "Mon-wed,sat"

The "*" character represents all possible values

Therefore, "*" in the sub-expression ( month ) represents the meaning of each month, "*" in the subexpression ( Day (week)) represents every day of the week

The "/" character is used to specify the increment of the numeric value

For example: "0/15" in sub-expressions (minutes) means starting from the No. 0 minute, every 15 minutes

"3/20" in the sub-expression (minutes) means that every 20 minutes (it is the same as "3,23,43") starting from the 3rd minute


“? "Character is used only for days (months) and days (weeks) of two sub-expressions, indicating that no value is specified

When one of the 2 sub-expressions is assigned a value, in order to avoid a conflict, you need to set the value of another subexpression to "? ”

The "L" character is used only for days (months) and days (weeks) of two sub-expressions, which is the abbreviation for the word "last"

But it has a different meaning in two sub-expressions.

In the day (month) subexpression, "L" represents the last day of the one-month

In the day (week) Self-expression, "L" represents the last day of one weeks, the SAT

If there is something specific before "L", it has other meanings.

For example: "6L" means the 6th day of the month, and "Fril" means the last Friday of the month.

Note: When using the "L" parameter, do not specify a list or range, as this can cause problems

字段 允许值 允许的特殊字符
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /

4, limitations--@Scheduled cron cannot specify the year of execution

That is, if we use the following scheduled tasks

    = "0 18 10 * *?" 2016-2016 ")    publicvoid  testtaskwithdate () {        logger.info (" Test 2016. Scheduled Tasks ");    }

The following error will be reported

Cron expression must consist of 6 fields (found 7 in "0 18 10 * *?) 2016-2016 ")
Org.springframework.beans.factory.BeanCreationException:Error creating Bean with Name ' Giftreceiverecordserviceimp ' defined in URL [jar:file:/users/zhengcanrui/work/git/seewoedu-train-server/train-web/target/train/web-inf/lib/ Train-server-2.0-snapshot.jar!/com/seewoedu/train/service/impl/giftreceiverecordserviceimp.class]: Initialization of Bean failed; Nested exception is java.lang.IllegalStateException:Encountered invalid @Scheduled method ' Testtaskwithdate ': Cron Expression must consist of 6 fields (found 7 in "0 18 10 * *?) 2016-2016 ") at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( Abstractautowirecapablebeanfactory.java:553) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( Abstractautowirecapablebeanfactory.java:482) at org.springframework.beans.factory.support.abstractbeanfactory$1.getObject (abstractbeanfactory.java:306) at Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( Defaultsingletonbeanregistry.java:230) at Org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (Abstractbeanfactory.java:60W) at Org.springframework.beans.factory.support.AbstractBeanFactory.getBean (Abstractbeanfactory.java:197) at Org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( Defaultlistablebeanfactory.java:772) at Org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( Abstractapplicationcontext.java:839) at Org.springframework.context.support.AbstractApplicationContext.refresh (Abstractapplicationcontext.java: 538) at Org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext ( Contextloader.java:444) at Org.springframework.web.context.ContextLoader.initWebApplicationContext (Contextloader.java:326) at org.springframework.web.context.ContextLoaderListener.contextInitialized (Contextloaderlistener.java: 107) at Org.apache.catalina.core.StandardContext.listenerStart (Standardcontext.java:4842) at Org.apache.catalina.core.StandardContext.startInternal (Standardcontext.java:5303) at Org.apache.catalina.util.LifecycleBase.start (Lifecyclebase.java:147) at Org.apache.catalina.core.ContainerBase.addChildInternal (Containerbase.java:725) at Org.apache.catalina.core.ContainerBase.addChild (Containerbase.java:701) at Org.apache.catalina.core.StandardHost.addChild (Standardhost.java:717) at org.apache.catalina.startup.HostConfig.manageApp (Hostconfig.java:1696) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:30S) at Org.apache.tomcat.util.modeler.BaseModelMBean.invoke (Basemodelmbean.java:300) at Com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke (Defaultmbeanserverinterceptor.java:819) at Com.sun.jmx.mbeanserver.JmxMBeanServer.invoke (Jmxmbeanserver.java:801) at Org.apache.catalina.mbeans.MBeanFactory.createStandardContext (Mbeanfactory.java:484) at Org.apache.catalina.mbeans.MBeanFactory.createStandardContext (Mbeanfactory.java:433) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:606) at Org.apache.tomcat.util.modeler.BaseModelMBean.invoke (Basemodelmbean.java:300) at Com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke (Defaultmbeanserverinterceptor.java:819) at Com.sun.jmx.mbeanserver.JmxMBeanServer.invoke (Jmxmbeanserver.java:801) at Javax.management.remote.rmi.RMIConnectionImpl.doOperation (Rmiconnectionimpl.java:1487) at javax.management.remote.rmi.rmiconnectionimpl.access$(rmiconnectionimpl.java:97) at Javax.management.remote.rmi.rmiconnectionimpl$privilegedoperation.run (Rmiconnectionimpl.java:1328) at Javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation (Rmiconnectionimpl.java:1420) at Javax.management.remote.rmi.RMIConnectionImpl.invoke (Rmiconnectionimpl.java:848) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:30S) at Sun.rmi.server.UnicastServerRef.dispatch (Unicastserverref.java:322) at sun.rmi.transport.transport$2.run (transport.java:202) at sun.rmi.transport.transport$2.run (transport.java:199) at java.security.AccessController.doPrivileged (Native Method) at Sun.rmi.transport.Transport.serviceCall (Tran Sport.java:198) at Sun.rmi.transport.tcp.TCPTransport.handleMessages (Tcptransport.java:567) at Sun.rmi.transport.tcp.tcptransport$connectionhandler.run0 (Tcptransport.java:828) at sun.rmi.transport.tcp.tcptransport$connectionhandler.access$(tcptransport.java:619) at sun.rmi.transport.tcp.tcptransport$connectionhandler$1.run (tcptransport.java:684) at sun.rmi.transport.tcp.tcptransport$connectionhandler$1.run (tcptransport.java:681) at java.security.AccessController.doPrivileged (Native Method) at Sun.rmi.transport.tcp.tcptransport$connectio Nhandler.run (Tcptransport.java:681) at Java.util.concurrent.ThreadPoolExecutor.runWorker (Threadpoolexecutor.java:1145) at Java.util.concurrent.threadpoolexecutor$worker.run (Threadpoolexecutor.java:615) at Java.lang.Thread.run (Thread.java:745) caused by:java.lang.IllegalStateException:Encountered invalid @Scheduled method' testtaskwithdate ': Cron expression must consist of 6 fields (found 7 in "0 18 10 * *?) 2016-2016 ") at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled ( Scheduledannotationbeanpostprocessor.java:405) at Org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization ( Scheduledannotationbeanpostprocessor.java:258) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization (Abstractautowirecapablebeanfactory.java:422) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( Abstractautowirecapablebeanfactory.java:1583) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( Abstractautowirecapablebeanfactory.java:545)    ... More
View Code

Cause of Error:

/***/privatevoidthrows  illegalargumentexception {    = Stringutils.tokenizetostringarray (expression, "");     if (Fields.length! = 6)        {thrownew illegalargumentexception (String.Format ("" "                + "Cron expression must consist of 6 fields (found%d in%s)", fields.length, expression));    }

Spring Taks does not support the annual bit timing, after all it is not quartz, it is simply a timed frame that joins the thread pool instead of the JDK timer.

Comments in the source code:

  *The pattern is a list of six single space-separated fields: representing   * second, minute, hour, day, month, weekday. Month and weekday names can be   * given as the first three letters of the English names.

Thanks: Thank you for reading!

Spring timed Task @scheduled

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.