日期:2014-05-17  浏览次数:20654 次

JSP 传参数给TimerTask
JSP页面
Timer timer = new Timer(true); 
TimerTask task=new TimerTask() {

public void run(){
 
select_Tables(re,out);报错:re,out 如何传参数到这里
 
}
};

timer.schedule(task,0,500);

------解决方案--------------------


public class AAA implements ServletContextListener
{

private Timer timer = null;

public void contextDestroyed(ServletContextEvent arg0) 
{
timer.cancel();
}
public void contextInitialized(ServletContextEvent arg0)
{
timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
内容
}
}, 0, 1000*60);
}
}

------解决方案--------------------
我的代码:给你借鉴

public class Task extends TimerTask {

private static Logger log=Logger.getLogger(Task.class);
private Timer timer;
private String sender;
private HashMap<Integer, String[]> mobiles;
private String smsContent;

public Task(){
}

public Task(Timer timer,HashMap<Integer, String[]> mobiles, String sender) { this.timer = timer;
this.mobiles = mobiles;
this.sender = sender;
}

// 取消计时器
public void stopTask() {
timer.cancel();
}

// 开始执行计时器操作
@Override
public void run() {
Date time = new Date();
if (time.getTime() > endtime.getTime()) {
log.debug("定时器停止了...");
stopTask();
} else {
try {
// 发送消息
log.debug("定时器执行了..."); api.SendGeneralMsg(mobiles, smsContent, sender); } catch (Exception e) {
// TODO Auto-generated catch block
log.debug("定时器异常:" + e.getMessage());
setResult(new ResultPackage(MessageCode.sms1036, e.getMessage()));
}
}
}

public Timer getTimer() {
return timer;
}

public void setTimer(Timer timer) {
this.timer = timer;
}

public HashMap<Integer, String[]> getMobiles() {
return mobiles;
}

public void setMobiles(HashMap<Integer, String[]> mobiles) {
this.mobiles = mobiles;
}

public String getSender() {
return sender;
}

public void setSender(String sender) {
this.sender = sender;
}

}

业务逻辑类:

/**
* 时钟对象
* @param task
* @return
*/
public static ResultPackage TimerSMSSend(Task task){
try{
Timer timer = new Timer(); 
task.setTimer(timer);
task.setEndtime(endtime);
// 执行频率5秒
timer.scheduleAtFixedRate(task, starttime, 5000);
return new ResultPackage(MessageCode.sms0017); 
}catch(Exception e){
System.out.println("时间转换异常:" + e.getMessage());
return new ResultPackage(MessageCode.sms1018, e.getMessage());
}
}

外层调用赋参数:
Task tsk = new Task();
tsk.setMobiles(map);
tsk.setSender(sender);
tsk.setSendType(sendType);
result = TimeTK.TimerSMSSend(tsk);


红字是外层传进去的参数。。。。部分代码已省略,,,这只是思路