Loading

SpringTask一:xml配置方式

一.pom.xml

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.20.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.20.RELEASE</version>
    </dependency>

二.任务类

public class TaskService {

    public void firstTask(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm:ss:ms");
        String format = simpleDateFormat.format(new Date());
        System.out.println("数据库备份时间1:"+format);
    }

    public void secondTask(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm:ss:ms");
        String format = simpleDateFormat.format(new Date());
        System.out.println("数据库备份时间2:"+format);
    }
}

三.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:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">
    <bean id="taskService" class="com.wj.TaskService">

    </bean>

    <!--配置定时规则-->
    <task:scheduled-tasks>
        <!--initial-delay:服务器启动后多少毫秒开始执行定时任务-->
        <!--fixed-delay:每隔多少毫秒执行一次定时任务-->
        <!--cron:可以指定复杂定时任务,前文Quartz有介绍,不再叙述-->
        <task:scheduled ref="taskService" method="firstTask" initial-delay="10000" fixed-delay="2000"/>
        <task:scheduled ref="taskService" method="secondTask" initial-delay="20000" fixed-delay="4000"/>
    </task:scheduled-tasks>

</beans>

四.运行效果:

 

posted @ 2020-04-06 17:42  秋风飒飒吹  阅读(870)  评论(0编辑  收藏  举报