前面两篇博客讲解了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定时任务是使用起来最方便,配置最简单的一种定时任务。大部分的需求他都可以满足,大家也去尝试一下吧。