本篇文章将在将介绍如何在spring中使用类似于Linux/Unix中的Cron的任务管理模块。
创建一个Cron任务的类
package com.example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class CronTasks {
private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 2000)
public void cronDemoTasks(){
System.out.println("CronTask: Hello, this is for test : " + dateFormat.format(new Date()));
}
}
修改DemoApplication
只需要加入@EnableScheduling注解即可
执行输出
因为使用out打出来的信息, 结果的确认在Console的输出即可看到.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.2.RELEASE)
2016-12-09 07:04:59.491 INFO 4092 --- [ main] com.example.DemoApplication : Starting DemoApplication on vcc-PC with PID 4092 (C:\Users\Administrator\IdeaProjects\demo\target\classes started by Administrator in C:\Users\Administrator\IdeaProjects\demo)
2016-12-09 07:04:59.495 INFO 4092 --- [ main] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2016-12-09 07:04:59.581 INFO 4092 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Fri Dec 09 07:04:59 CST 2016]; root of context hierarchy
2016-12-09 07:05:01.304 INFO 4092 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-09 07:05:01.319 INFO 4092 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-12-09 07:05:01.321 INFO 4092 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-09 07:05:01.492 INFO 4092 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-12-09 07:05:01.493 INFO 4092 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1922 ms
2016-12-09 07:05:01.621 INFO 4092 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-09 07:05:01.625 INFO 4092 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-09 07:05:01.625 INFO 4092 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-09 07:05:01.625 INFO 4092 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-09 07:05:01.626 INFO 4092 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-09 07:05:01.879 INFO 4092 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Fri Dec 09 07:04:59 CST 2016]; root of context hierarchy
2016-12-09 07:05:01.952 INFO 4092 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public com.example.User com.example.DemoApplication.greeting(java.lang.String)
2016-12-09 07:05:01.954 INFO 4092 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-12-09 07:05:01.954 INFO 4092 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-12-09 07:05:01.980 INFO 4092 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-09 07:05:01.980 INFO 4092 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-09 07:05:02.017 INFO 4092 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-09 07:05:02.239 INFO 4092 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-12-09 07:05:02.249 INFO 4092 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
CronTask: Hello, this is for test : 07:05:02
2016-12-09 07:05:02.299 INFO 4092 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-09 07:05:02.303 INFO 4092 --- [ main] com.example.DemoApplication : Started DemoApplication in 3.341 seconds (JVM running for 3.831)
CronTask: Hello, this is for test : 07:05:04
CronTask: Hello, this is for test : 07:05:06
CronTask: Hello, this is for test : 07:05:08
CronTask: Hello, this is for test : 07:05:10
CronTask: Hello, this is for test : 07:05:12
CronTask: Hello, this is for test : 07:05:14
CronTask: Hello, this is for test : 07:05:16
CronTask: Hello, this is for test : 07:05:18
CronTask: Hello, this is for test : 07:05:20
CronTask: Hello, this is for test : 07:05:22
......
可以清楚地看到,每格两秒,此Task就会被调用执行一次。
Cron风格方式
与Ctrontab写法的区别,被人熟知的Crontab的写法如下:
项目 | 说明 |
---|---|
格式 | * * * * * command |
说明 | 分 时 日 月 周 命令 |
第1列 | 分钟1~59 每分钟用或者 /1表示 |
第2列 | 小时1~23(0表示0点) |
第3列 | 日期1~31 |
第4列 | 月份1~12 |
第5列 | 星期0~6(0表示星期天) |
第6列 | 要运行的命令 |
而Scheduling则是如下的格式
项目 | 说明 |
---|---|
格式 | * * * * * * |
第1列 | 秒 |
第2列 | 分钟 |
第3列 | 小时 |
第4列 | 日期 |
第5列 | 月份 |
第6列 | 星期 |
简单来说,精度精确到秒,命令行无需指定,显然此处是使用spring的类反射机制由声明的注解处的函数所提供对应定期调用的功能。
Cron风格常用写法
写法 | 说明 |
---|---|
“0 0 * * * *” | the top of every hour of every day. |
“/10 * * * *” | every ten seconds. |
“0 0 8-10 * * *” | 8, 9 and 10 o’clock of every day. |
“0 * 6,19 * * *” | 6:00 AM and 7:00 PM every day. |
“0 0/30 8-10 * * *” | 8:00, 8:30, 9:00, 9:30 and 10 o’clock every day. |
“0 0 9-17 * * MON-FRI” | on the hour nine-to-five weekdays |
“0 0 0 25 12 ?” | every Christmas Day at midnight |
Cron风格验证
将fixedRate的设定改成cron风格,变成没3秒调用一次。
@Scheduled(fixedRate = 2000)
-〉
@Scheduled(cron=”/3 * * * *”)
结果确认
如下则是部分输出结果,从中可以清晰地确认到3秒钟被调用的结果。
CronTask: Hello, this is for test : 07:23:03
CronTask: Hello, this is for test : 07:23:06
CronTask: Hello, this is for test : 07:23:09
CronTask: Hello, this is for test : 07:23:12