[java]spring-task定时任务

前面两篇博客讲解了Quartz来实现定时任务,不过spring3以后,自己封装了spring的task来实现定时任务,配置起来不要太简单,用起来真的很方便,下面咱们来一起实现一下这个task

spring-task简介

spring task,可以将它比作一个轻量级的Quartz,使用起来很简单,不过形式没有quartz多样,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式。

spring-task实例

下面咱们一起来敲一个spring-task的实例,本例将使用注解方式来实现,因为他更简便。

环境

spring 4.0.6
junit 4

定时任务类

package com.springtask.TestTask;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Created by L on 2017-07-25.
 */
@Component
public class TaskJob {

    @Scheduled(cron = "0/5 * * * * ?")
    public void execute(){
        System.out.println("我是定时执行的job"+ new Date());
    }
}

配置文件

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

<!--配置包扫描-->
    <context:component-scan base-package="com.springtask.TestTask"/>

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

到此为止,所有配置已经完成,spring的cron配置与quartz的大同小异,大家可以自行定制。

测试

然后我们写一个测试类

package com.springtask.TestTask.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

/**
 * Created by L on 2017-07-25.
 */
public class TaskJobTest {

    @Test
    public void test() throws InterruptedException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        Thread.sleep(60000);
    }
}

结果

来看一下咱们的显示结果
这里写图片描述

总结

总的来说,spring的task定时任务是使用起来最方便,配置最简单的一种定时任务。大部分的需求他都可以满足,大家也去尝试一下吧。

评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盖丽男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值