【Spring框架07】定时任务

【Spring框架07】定时任务

思维导图

在这里插入图片描述

一、基于xml方式配置

1.定时任务命名空间添加

<?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-4.0.xsd">

<!--    配置定时任务-->
    <bean id="jobTask" class="com.lcy.task.jobTask"></bean>
    <task:scheduled-tasks>
        <task:scheduled ref="jobTask" method="job01" cron="0/2 * * * * ? "/>
        <task:scheduled ref="jobTask" method="job02" cron="0/5 * * * * ? "/>
    </task:scheduled-tasks>
</beans>

2.定时任务方法代码

public class jobTask {
    public void job01(){
        System.out.println("任务一》》》》》》……");
    }
    public void job02(){
        System.out.println("任务二》》》》》》……");
    }
}

3.定时任务配置测试

public class jobTaskTest extends TestCase {
    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("spring.xml");
    }
}

二、基于注解

1.配置定时任务驱动

和之前的步骤差不多,但是需要在spring.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-4.0.xsd">

<!--    开启定时任务注解驱动-->
    <task:annotation-driven/>
<!--    开启bean扫描-->
    <bean id="jobTest01" class="com.lcy.task.jobTest01"></bean>
</beans>

2.定时任务代码

public class jobTest01 {
    @Scheduled(cron="0/2 * * * * ? ")
    public void job01(){
        System.out.println("任务一》》》》》》……");
    }
    @Scheduled(cron="0/5 * * * * ? ")
    public void job02(){
        System.out.println("任务二》》》》》》……");
    }
}

3.编写测试类运行

public class jobTaskTest extends TestCase {
    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("spring.xml");
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值