首页 / JAVA / java – 取消定时器
java – 取消定时器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 取消定时器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2409字,纯文字阅读大概需要4分钟。
内容图文
![java – 取消定时器](/upload/InfoBanner/zyjiaocheng/757/be41b536289c406d97a9ccce85ccb1e0.jpg)
我已经实现了一个令牌系统,它可以分配固定数量的令牌.分配的每个令牌启动一个Timer,该Timer在几分钟后到期并清除该令牌槽以供重用.如果用户在计时器到期之前验证令牌,则应该取消计时器并使用另一个令牌有效期重置.我似乎无法从计时器线程外取消计时器,这是预期的行为.片段如下:
/**
* Fills one of the available slots with a new session key
* @param sessionKey
* @return true on slot fill success - false on fail
*/
public boolean fillSlot(String sessionKey)
{
if(count<MAXCOUNT)
{
//Add key to slot
slots.add(sessionKey);
//Up the key count
upCount();
//Set up expiry timer
Timer timer = new Timer();
timer.schedule(new ExpiringTokentask(timer,sessionKey), EXPIRY_TIME);
timers.put(sessionKey, timer);
return true;
}
return false;
}
/**
* Check if a given key is stored in the slots
* reset timer every time key is checked
* @param sessionKey
* @return true on key found false on not found
*/
public boolean checkSlot(String sessionKey)
{
//TODO: More efficient key search and storage for larger user sets
//TODO: Upgrade from memory array to h2 embedded DB
for(int i=0;i<slots.size();i++)
{
if(sessionKey.equals(slots.get(i)))
{
//Reset timer
Timer timer = timers.get(sessionKey);
//Can't seem to do this
// timer.cancel();
timer.schedule(new ExpiringTokentask(timer,sessionKey), EXPIRY_TIME);
//Return token validation
return true;
}
}
return false;
}
private class ExpiringTokentask extends TimerTask
{
private Timer timer;
private String expireToken;
public ExpiringTokentask(Timer timer, String sessionKey)
{
this.timer = timer;
this.expireToken = sessionKey;
System.out.println(sessionKey);
}
public void run() {
System.out.format("Time's up!%n");
clearSlot(expireToken);
timer.cancel(); //Terminate the timer thread
}
}
解决方法:
如前所述,您可以取消提交给计时器的TimerTask而不是取消计时器,这样您就不需要更新更多的计时器.
你在做什么:
timer.cancel();
timer.schedule(...);
将抛出IllegalStateExceptions,因为您无法在已取消的计时器上安排新任务.
所以不要这样做:timer.cancel()
使您的映射成为从会话密钥到TimerTasks的映射,并取消TimerTask而不是Timer.这样您就不必新建新的计时器,并且在取消一个或多个任务后,计时器将按预期工作.您还可以使用一个计时器来处理多个会话.现在你正在制作一个Timer,因此每个会话一个线程.
另一方面,您不应该使用java.util.Timer.如果任何TimerTasks抛出异常会发生什么?你的计时器将被杀死,永远不会再次运行!如果你的一个TimerTasks很慢或无限期阻塞怎么办?该定时器上的任何其他TimerTasks将无法执行.请考虑使用ScheduledThreadPoolExecutor.我确信java.util.Timer将在下一个Java版本中弃用.
内容总结
以上是互联网集市为您收集整理的java – 取消定时器全部内容,希望文章能够帮你解决java – 取消定时器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。