开发环境
- JDK 8
- spring版本 4.3.8
参考文章
https://www.cnblogs.com/zjdxr-up/p/7778135.html
https://blog.csdn.net/qq_33556185/article/details/51852537
名称空间的引入
<beans default-autowire="byName"
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.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.3.xsd">
</beans>
注入一个bean
<bean id="fastDFSService" name="fastDFSService"
class="fastdfs.service.FastDFSServiceImpl" scope="prototype">
</bean>
task标签定义定时的任务
其中ref为指定哪个类, method为指定哪个方法进行定时任务. cron为确定在何时触发该方法.
cron="* * * * * ?"
表示每秒钟触发该方法
<task:scheduled-tasks>
<task:scheduled ref="fastDFSService" method="deleteFastFile" cron="* * * * * ?" />
</task:scheduled-tasks>
cron表达式的含义 如下图
常用的cron表达式
* second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
* 0 * * * * MON-FRI
* 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
* 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
* 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
* 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
* 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
* "0/4 * * * * MON-SAT") //每4秒执行一次
在spring的cron表达式中, 只允许有6个字段, 否则会报错. 但可以逗号进行同一个字段的枚举