一、@Scheduled( cron="* * * * *" )
1.作用:
每隔一段时间 , 自动同步缓存!
2.如何使用? ( 具体使用看如下案例 ? )
在需要使用的方法上添加@Scheduled注解以及使用cron表达式.
3.cron表达式( 两种 )
①cron=“秒 分 时 日 月 周 年”
②cron=“秒 分 时 日 月 周” // 年份可为空!
简述: 也就是将年月日 , 时分秒 ( 倒过来写 )
Cron表达式范例:
“10 10 1 20 * ?” 每月20号1点10分10秒触发任务
“10 10 1 20 10 ? 2018” 2018年10月20号1点10分10秒触发任务
“10 10 1 ? 10 SUN 2018” 2018年10月每周日1点10分10秒触发任务
( 注: 由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置? )
附上一个在线表达式生成网站:
http://qqe2.com/cron
4.案例: 使用@Scheduled将信息添加到redis缓存.
1.添加spring/applicationContext-task.xml文件( 扫描@Component注解 , 开启定时任务 )
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.jxj.task" />
<!-- 开启定时任务 -->
<task:annotation-driven />
</beans>
2.web.xml配置( 加载spring容器! )
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!--加载spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
3.缓存添加.( 注: 包要导对 )
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
// 将当前类交给spring容器处理!
@Component
public class RedisTask {
@Resource
private RedisTemplate<String , Object> redisTemplate;
// 使用注解 , 对当前方法执行定时任务!
@Scheduled(cron = "00 17 19 26 12 ?")
public void setItemCatToRedis(){
redisTemplate.boundHashOps("user").put("name" , "老王");
redisTemplate.boundHashOps("user").put("age" , "35");
System.out.println("定时器执行了...");
}
}
如图: ( 到指定的时间 , 就加入到缓存redis中了 )