实现定时任务【Timer+TimerTask】

在实现定时任务的时候,必须面对多线程的问题,这里先贴两段代码,记录一下(还是实现短信验证码的功能,定时失效)

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();
		}
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值