Spring - 使用@Scheduled cron表達式 ,定時往redis中添加緩存.

一、@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中了 )
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章