使用 Spring的定时任务(任务调度)<task:scheduled-tasks>

Spring内部有一个task是Spring自带的一个设定时间自动任务调度,提供了两种方式进行配置,一种是注解的方式,而另外一种就是XML配置方式了。注解方式比较简洁,XML配置方式相对而言有些繁琐,但是应用场景的不同,两者又各有优点,所以具体使用还是根据需求来划分。因为任务调度这样的需求,通常改动都是比较多的,如果用注解的方式改动就变得麻烦了,必须去重新编译。所以更多的时候我选择用XML配置的方式。

下面就介绍一下两种方式的配置:

第一种:XML配置方式

第一步:编写作业类

即普通的pojo,如下:

import org.springframework.stereotype.Service;  
@Service  
public class TaskJob {  
      
    public void job1() {  
        System.out.println(“任务进行中。。。”);  
    }  
} 

第二步:添加spring-task配置文件,相关头信息如下:

<?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:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">

    <task:scheduled-tasks>

        <task:scheduled ref="taskJob" method="job1" cron="0 0 5 * * ?"/> </task:scheduled-tasks> 

</beans>

说明:ref参数指定任务类,method指定需要运行的方法,cron及cronExpression表达式见文章结尾。

第三步:在spring配置文件中引入spring-task配置文件.

。。。。。
<!-- 引入Spring的任务配置文件。 -->
    <import resource="xxx.xml" />
。。。。。

----------------------------------------------------

第二种:使用注解形式

首先看下源文件中@Scheduled注解的定义

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Scheduled  
{  
  public abstract String cron();  
  
  public abstract long fixedDelay();  
  
  public abstract long fixedRate();  
} 

可以看出该注解有三个方法或者叫参数,分别表示的意思是:

cron:指定cron表达式

fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。

fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

第一步:编写pojo

mport org.springframework.scheduling.annotation.Scheduled;    
import org.springframework.stereotype.Component;  
  
@Component(“taskJob”)  
public class TaskJob {  
    @Scheduled(cron = "0 0 3 * * ?")  
    public void job1() {  
        System.out.println(“任务进行中。。。”);  
    }  
} 

第二步:在spring配置文件开启task:

<task:annotation-driven/>
cronExpression的配置说明
字段   允许值   允许的特殊字符
秒    0-59    , - * /0-59    , - * /
小时    0-23    , - * /
日期    1-31    , - * ? / L W C
月份    1-12 或者 JAN-DEC    , - * /
星期    1-7 或者 SUN-SAT    , - * ? / L C #
年(可选)    留空, 1970-2099    , - * / 
- 区间  
* 通配符  
? 你不想设置那个字段
下面只例出几个式子

CRON表达式    含义 
"0 0 12 * * ?"    每天中午十二点触发 
"0 15 10 ? * *"    每天早上10:15触发 
"0 15 10 * * ?"    每天早上10:15触发 
"0 15 10 * * ? *"    每天早上10:15触发 
"0 15 10 * * ? 2005"    2005年的每天早上10:15触发 
"0 * 14 * * ?"    每天从下午2点开始到2点59分每分钟一次触发 
"0 0/5 14 * * ?"    每天从下午2点开始到2:55分结束每5分钟一次触发 
"0 0/5 14,18 * * ?"    每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 
"0 0-5 14 * * ?"    每天14:00至14:05每分钟一次触发 
"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44触发 
"0 15 10 ? * MON-FRI"    每个周一、周二、周三、周四、周五的10:15触发 

===============================

这种是使用配置文件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:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.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-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<!--    <task:annotation-driven/>-->


    <bean id="heartBeat" class="devp.machine.business.controller.HeartBeatTask" />

<!--    <task:scheduler id="myScheduler" pool-size="10" />-->
    <task:scheduled-tasks >
             <task:scheduled ref="heartBeat" method="runTask1" cron="0 */1 * * * ?"/>
    </task:scheduled-tasks>
</beans>

定时任务对应的类:

package devp.machine.business.controller;

import devp.machine.api.service.ICenterService;
import devp.machine.impl.dao.ResourceCountDao;
import devp.machine.impl.service.CenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

//@Service("devp.machine.business.controller.HeartBeatTask")
@Service()
//@Component
public class HeartBeatTask {

    /**
     * 定时完成  统计数据资源中心的数据
     */

    @Autowired
    private ICenterService centerService;
    @Autowired
    private CenterService centerServiceImpl;

    @Autowired
    private ResourceCountDao resourceCountDao;

    // 每一个小时执行一次
//    @Scheduled(cron = "0 0 */1 * * ?")
    // 每一分钟执行一次
//    @Scheduled(cron = "0 */1 * * * ?")
    public void runTask1(){

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>定时任务开始启动>>>>>>>>>>>>>>>>>>");
        try{
            // 获取查出来的数据 放在新的表中
            Map<String, List<Map<String, Object>>> data = centerService.dataCount();
            System.out.println(">>>>>>>>>>>>>>>>>>>>>查询数据完成开始新增数据库>>>>>>>>>>>>>>>>>>>>>>");
            if(!data.isEmpty()){

                // 清空表
                String deleteSql = "delete from resource_count";
                int delete = resourceCountDao.executeSQL(deleteSql);
                System.out.println(">>>>>>>>>>>>>>>>清空表 删除的条数 count= "+delete+"<<<<<<<<<<<<<<<<<<");

                List<Map<String, Object>> entity = data.get("entity");
                List<Map<String, Object>> relation = data.get("relation");
                List<Map<String, Object>> text = data.get("text");
                List<Map<String, Object>> relationState3 = data.get("relationState3");

                // 循环 存入数据库表 resource_count 中

                System.out.println(">>>>>>>>>>>>>>>>>>>>开始新增数据>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                if(delete != 0){
                    Integer  entityCount = centerServiceImpl.insertEntityList(entity);
                    Integer  relationCount = centerServiceImpl.insertRelationList(relation);
                    Integer  relationState3Count = centerServiceImpl.insertRelationState3List(relationState3);
                    Integer  textCount =centerServiceImpl.insertTextList(text);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
原文地址:https://www.cnblogs.com/yishuo/p/13220272.html