在实现定时任务的时候,必须面对多线程的问题,这里先贴两段代码,记录一下(还是实现短信验证码的功能,定时失效)
1)继承TimerTask类实现自己的定时任务
package com.util;
import java.util.TimerTask;
import javax.servlet.http.HttpSession;
public class TimeUtil extends TimerTask {
private HttpSession session;//设置session
private String attr;
public TimeUtil() {}
public TimeUtil(HttpSession session,String attr) {
super();
this.session = session;
this.attr = attr;
}
@Override
public void run() {
/**
* 将session中的msgCode清除
*/
session.removeAttribute(attr);
//long time = scheduledExecutionTime();
System.out.println("开始执行删除任务:"+System.currentTimeMillis());
}
}
2)在action中实现发送短信的功能,并开启新的线程,在规定时间后删除session中保留的验证码,让验证失效
/**
* 忘记密码,发送短信验证码,并将验证码放入session中,十分钟有效期
* @param mapping
* @param form
* @param req
* @param res
* @throws Exception
*/
public void sendMsg(
ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) throws Exception {
// 将form 转型为User
User user = (User) form;
// 2 应用业务逻辑
Map<String, Object> map = new HashMap<String,Object>();
PrintWriter writer= null;
try{
final String phone =user.getPhone(); //手机号
//校验 验证码 发送次数
Integer time = phoneMap.get(phone);
System.out.println(maxTime+" "+maxEfficTime);
HttpSession session = req.getSession();//获取session对象
String msgCode = RandomUtil.getMsgCode(4);//验证码
String msg = RandomUtil.getMsg(msgCode, phone);//短信
SendPhoneMsgUtil spmu = new SendPhoneMsgUtil();
String sms = spmu.SendSms(phone,msg);//发送验证码,sms是状态码
System.out.println("状态:"+sms+"code:"+msgCode);
//校验码保存到session中(使用timeTask在2分钟内将其删除)
if(Integer.valueOf(sms)<=0){
throw new RuntimeException("发送失败:失败代码:"+sms);
}
if(time==null){//由于time是Integer类型,需要将null做一个转换,不能直接运算
time=0;
}
phoneMap.put(phone, time++);
Timer timer = new Timer();
session.setAttribute("msgCode", msgCode);
System.out.println("开始计时:"+System.currentTimeMillis());
timer.schedule(new TimeUtil(session, "msgCode"),maxEfficTime*60*1000);//2分钟后执行TimeUtil对象的run方法
map.put("maxEfficTime",maxEfficTime*60);
map.put("result", true);
res.setContentType("application/json;charset=UTF-8");
String jsonString = JSONObject.toJSONString(map);
writer = res.getWriter();
writer.print(jsonString);
}catch(Exception e){
e.printStackTrace();
}finally{
writer.close();
}
}