一、注解方式
1. applicationContext.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
//必须的
http://www.springframework.org/schema/task
//必须的
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 配置任务扫描-->
<task:annotation-driven/>//必须的
<!-- 扫描任务-->
//扫描包路径为定时方法所在包
<context:component-scan base-package="com.online.college.opt.controller"/>//必须的
</beans>
2.设置需要执行的定时方法
package com.online.college.opt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.Random;
@Controller
@EnableScheduling
public class timerTaskController {
@Autowired
private ICourseService courseService;
/**
* 定时添加course表中学习人数基数
*/
//设置为每天凌晨两点执行一次
@Scheduled(cron = "0 0 2 * * ?")
public void addBaseCount(){
Random random = new Random();
List<Course> courses = courseService.queryAll();
for (Course cours : courses) {
int count = random.nextInt(100) + 270;
cours.setStudyBaseCount(cours.getStudyBaseCount() + count);
courseService.updateSelectivity(cours);
}
}
}
二、配置文件直接设置
1、圈起来的一定不能少
2、配置定时任务规则
3、编写定时方法
补充: 定时时间设置
1.时间格式为: [秒] [分] [时] [日] [月] [周] [年]
2. 日和周不能同时设定值
3. * 号表示包含所有合法值; ? 表示不指定值,只能作用在日或周上; , 用来给某个域指定值列表; / 用于表示时间表递增; - 用于指定一个范围;
4. 例子:
“0 0 12 * ?" 每天中午12点触发
"0 15 10 * * ?” 每天上午10:15触发
“0 * /5 * * * ?” 每隔五分钟执行一次
“0 * 14 * * ?” 每天14点到14:59分,每1分钟执行一次
“0 0-5 14 * * ?” 每天14点到14:05分,每1分钟执行一次
“0 0 0/1 * * ?” 每个整点执行一次