今天碰到个问题,需要达到一个功能,使服务器定时执行某一个事件,后来想到了使用spring定制任务。
下面是配置 spring
<bean id="synNbrAccountTask" class="com.zlinfo.util.AddUserLogTimer" > <!-- 这里是你要执行的事件 -->
<property name="userService" ref="userService"></property> <!-- 这里是注入的service -->
<property name="userLogService" ref="userLogService"></property>
</bean>
<bean id="synNbrAccountTaskInfo" class="org.springframework.scheduling.timer.ScheduledTimerTask" >
<property name="delay">
<value>5000</value> <!-- 这里是延迟多少秒执行 -->
</property>
<property name="period">
<value>43200000</value> <!-- 86400000为24小时 --> <!--这里是间隔多长事件执行一次事件
</property>
<property name="timerTask">
<ref local="synNbrAccountTask"/>
</property>
</bean>
<bean id="timerBean" class="org.springframework.scheduling.timer.TimerFactoryBean" >
<property name="scheduledTimerTasks" >
<ref bean="synNbrAccountTaskInfo" />
</property>
</bean>
下面是我自己要执行的事件,这个类一定要继承TimerTask,重写run方法
package com.zlinfo.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import com.zlinfo.dao.UserDao;
import com.zlinfo.dao.impl.UserDaoImpl;
import com.zlinfo.model.User;
import com.zlinfo.model.UserLog;
import com.zlinfo.service.UserLogService;
import com.zlinfo.service.UserService;
/**
* 定义定时器 每天的17点添加所有员工的日志主表
*
* @author Administrator
*
*/
public class AddUserLogTimer extends TimerTask {
private UserLogService userLogService;
private UserService userService;
public UserLogService getUserLogService() {
return userLogService;
}
public void setUserLogService(UserLogService userLogService) {
this.userLogService = userLogService;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public void run() {
//先检查今天的数据是否插入
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
List<UserLog> checkUserLogs = userLogService.userLogList(new UserLog());
boolean falg = false;
for(UserLog ul : checkUserLogs){
//如果UserLog表中插入了今天的数据,则不用再进行插入
if(df.format(ul.getLogTime()).equals(df.format(new Date()))){
falg = true;
}
}
if(!falg){
User user = new User();
List<User> users = userService.list(user);
for (User u : users) {
UserLog ul = new UserLog();
String time = df.format(new Date());
try {
ul.setLogTime(df.parse(time));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ul.setLogUserName(u.getName());
ul.setLogUserId(u.getId());
ul.setLogDept(u.getDept_name());
ul.setLogAssess("正常");
userLogService.insert(ul);
System.out.println("添加了一个用户");
}
}
}
}