SSM定时任务

spring定时任务(@Scheduled注解)


首先

有时会遇到要求程序在某个时间点定时执行的需求,例如每日凌晨计算昨日销量等。上网查,发现@Scheduled注解可以用上。需要在springMVC里使用spring的定时任务,下面介绍一下方法


其次

1、springmvc.xml

  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    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/context    
    http://www.springframework.org/schema/context/spring-context-4.3.xsd    
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/mvc    
    http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
	http://www.springframework.org/schema/task 
	http://www.springframework.org/schema/task/spring-task-4.1.xsd">

	<context:component-scan base-package="com.xxx.**.controller" />  
	
    
    <task:executor id="executor" pool-size="5" /> 
    
    <task:scheduler id="scheduler" pool-size="10" /> 
    
    <task:annotation-driven executor="executor" scheduler="scheduler" />

(1)xmlns加一行
xmlns:task=“http://www.springframework.org/schema/task”

(2)xsi:最后加两行
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd

(3)启用注解驱动的定时任务1

2、写定时任务

这里直接写在了controller文件夹里,放在包扫描的路径下2
cron表达式里写执行的时机

@Component
public class TimerTask {
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	private TimerTaskService timerTaskService;
	
    /**
     * 定时执行
     * 数据分析,需每日计算昨日新增量
     */
    @Scheduled(cron = "0 0 0 * * ?")//执行时间(每天0点)
    public void dataAnalysis(){
        System.out.println("开始执行");
        /***************************这里面是想要执行的方法***********************/
    	try {
        	//获取缓存中“todayData”,用来存入“yesterdayData”
            Map<Object,Object> yesterdayData = redisTemplate.opsForHash().entries("todayData");  
            System.out.println("通过entries(H key)方法获取变量中的键值对:" + yesterdayData);  
            //将其存入“yesterdayData”缓存中
            redisTemplate.opsForHash().putAll("yesterdayData", yesterdayData);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("缓存中今日数据转昨日数据失败"); 
		}
    	Map<Object, Object> todayData = timerTaskService.getCounter();
    	redisTemplate.opsForHash().putAll("todayData", todayData);
    	System.out.println("执行结束");
    }
}

最后
参考


  1. task:scheduler和task:executor的解析 ↩︎

  2. 包扫描 ↩︎

你可能感兴趣的:(java)