spring task定时任务(一)

项目地址:https://github.com/snjl/spring.springtask.git

SprngTask没有专门的包,其核心类位于spring-context包中。所以引入spring的核心包此功能即可使用。

  在实际的项目中,我们经常将job作为action层,在job中注入service去操作底层的dao,或者定时的向其他系统拉取数据,再或者向其他系统推送数据。

xml配置文件applicationContext.xml:

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" 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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="org.task.app"/>

<!-- 定时器开关-->
<task:annotation-driven />
</beans>

SpringTimer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package org.task.app;

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

import java.util.Date;

/**
* @author 34924
*/
@Component
public class SpringTimer {
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
public void myTest(){
System.out.println("进入测试 " + new Date());
}
}

测试类TaskTest.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package org.task.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.task.app.SpringTimer;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class TaskTest {

@Autowired
SpringTimer springTimerTest;

@Test
public void springTask() {
try{
Thread.sleep(1000000);
}catch(Exception e){
e.printStackTrace();
}
}

}

log:

1
2
3
4
5
6
进入测试  Fri Nov 30 21:39:20 CST 2018
进入测试 Fri Nov 30 21:39:25 CST 2018
进入测试 Fri Nov 30 21:39:30 CST 2018
进入测试 Fri Nov 30 21:39:35 CST 2018
进入测试 Fri Nov 30 21:39:40 CST 2018
进入测试 Fri Nov 30 21:39:45 CST 2018

-------------本文结束 感谢您的阅读-------------