spring timing task @Scheduled details

  • 2020-06-01 09:37:28
  • OfStack

1. Configuration files


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">

 <!--  Timing task related configuration  -->
 <task:executor id="executor" pool-size="10" queue-capacity="128"/>
 <task:scheduler id="scheduler" pool-size="10"/>
 <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/>

</beans>

2. Call

There are two ways to use it

1) if it is necessary to execute at a fixed rate, just change the name of the property specified in the annotation to fixedRate. The following method will invoke 1 execution at a fixed rate of 5s. This cycle is based on the starting time of the above 1 task.


@Scheduled(fixedDelay = 5000)
 public void testTask() {
  logger.info(" Test timing task ");
 }

2) the expression cron can be used to realize the regular call, such as: call in the early morning every day. See the following for the detailed parameters related to cron


@Scheduled(cron = "cron = "0 0 2 * * ?"")
 public void testTaskWithDate() {
  logger.info(" test 2016. Timing task ");
 }

3. Significance of cron related parameters

An cron expression has at least six (and possibly seven) time elements separated by Spaces.

In order

59 seconds (0 ~) Minutes (0-59) Hours (0~23) Days (months) (0-31, but you need to consider the number of days in 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 is

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

0, 0, 10,14,16 * * ? B: ten in the morning, two in the afternoon, four every day 0 0/30 9-17 * * ? Every half hour from 9 to 5 0 0 12 & # 63; * WED stands for 12 noon every 3 days "0, 0, 12 * * ?" It's triggered every day at 12 noon "0 15 10 & # 63; * *" triggered at 10:15 am every day "0, 15, 10 * * ?" Triggered every morning at 10:15 a.m "0, 15, 10 * * ? *" triggered every morning at 10:15 a.m "0, 15, 10 * * ? "2005" triggered every morning at 10:15 in 2005 "0 * 14 * * ?" Triggered every minute between 2 p.m. and 2:59 p.m "0, 0, 5, 14 * * ?" Trigger every 5 minutes between 2 p.m. and 2:55 p.m "0 0/5 14,18 * * ?" Triggered every 5 minutes between 2 p.m. and 2:55 p.m. and between 6 p.m. and 6:55 p.m "0, 0, minus 5, 14 * * ?" Triggered every minute between 2 p.m. and 2:05 p.m "0 10 44 14 & # 63; 3 WED" is triggered at 2:10 p.m. and 2:44 p.m. on wednesdays in March each year "0 15 10 & # 63; * MON-FRI "triggers at 10:15 am on weekdays 1 through 5 "0, 15, 10, 15 * ?" Triggered at 10:15 am on the 15th of each month "0 15 10 L * ?" Triggered at 10:15 a.m. on the last day of each month "0 15 10 & # 63; * 6L" triggered at 10:15 am on the last Friday of the first week of each month "0 15 10 & # 63; * 6L 2002-2005" triggered at 10:15 am on the last Friday of the last week of each month from 2002 to 2005 "0 15 10 & # 63; * 6#3" triggered at 10:15 am on the 5th day of the 3rd week of each month

Some subexpressions can contain ranges or lists

For example, the subexpression (day (week)) can be "MON-FRI", "MON, WED, FRI", "MON-WED,SAT"

The "*" character represents all possible values

Thus, "*" in the subexpression (month) represents the meaning of each month, and "*" in the subexpression (day (week)) represents each day of the week

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

For example, "0/15" in the subexpression (minutes) means every 15 minutes from the 0th minute

The "3/20" in the subexpression (minutes) means that every 20 minutes from the third minute (it is the same as "3, 23, 43") means 1


"?" The character is used only for the day (month) and day (week) subexpressions, indicating that no value is specified

When 1 of the 2 subexpression is specified, the value of the other subexpression needs to be set to "? "to avoid collisions.

The "L" character is used only for the subexpressions day (month) and day (week), which is an abbreviation of the word "last"

But it has a different meaning in the two subexpression.

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

In the day (week) from expression, "L" represents the last day of a week, which is SAT

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

For example, "6L" means the last six days of the month, and "FRIL" means the last five weeks 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 -- cron @Scheduled cannot specify the year of execution

That is, if we use the following timing task


@Scheduled(cron = "0 18 10 * * ? 2016-2016")
  public void testTaskWithDate() {
    logger.info(" test 2016. Timing task ");
  }

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:302)
 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: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 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$300(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:606)
 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(Transport.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$400(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$ConnectionHandler.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)
 ... 58 more

Error reason:


/**
 * Parse the given pattern expression.
 */
private void parse(String expression) throws IllegalArgumentException {
 String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
 if (fields.length != 6) {
  throw new IllegalArgumentException(String.format(""
    + "cron expression must consist of 6 fields (found %d in %s)", fields.length, expression));
 }

spring taks does not support annual timing. It is not quartz after all, just a simple timing framework that joins the thread pool compared to jdk Timer.

However, there is a problem with setting the year, which is that when you start the project after this time, it will directly report an memory leak error, which roughly means that your scheduled task will never be executed, resulting in the failure of project 1.

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.

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: