• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Javaweb 定时器功能代码实例

java 搞代码 4年前 (2022-01-05) 25次浏览 已收录 0个评论

这篇文章主要介绍了Javaweb 定时器功能代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在Java的6.0版本中新增了concurrent包,这个包是用作线程同步的包,提供了很多工具类。

其中定时器就是其中之一。近期在做一个项目,在项目中要实现启动Web服务的同时启动一个任务,要求此任务为守护进程,定时调用一些任务操作代码。在网上搜索相关的实现,综合考虑得出一个解决方案。方案是:使用tomcat服务器的监听器类作守护进程,调用concurrent包提供的定时器,最后在定时器来源gao($daima.com搞@代@#码网中调用操作实现代码。具体实现类Translator在这里不再给出,将其替换为自己需要的实现类即可。

1.任务类

 import java.util.TimerTask; import javax.servlet.ServletContext; public class MyTask extends TimerTask{ private ServletContext context = null; public CleanTpIpTask(ServletContext servletContext) { this.context = servletContext; } @Override public void run() { //定时任务逻辑代码 } }

2.监听类

 import java.util.Calendar; import java.util.Date; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyTaskListener implements ServletContextListener { private java.util.Timer timer = null; MyTask myTask = null; public void contextDestroyed(ServletContextEvent arg0) { timer.cancel(); } public void contextInitialized(ServletContextEvent arg0) { Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); c.set(year, month, day, 3, 0, 0);//项目启动当天凌晨3点执行1次,如果已经超过凌晨3点,立刻执行 Date date = c.getTime(); timer = new java.util.Timer(true); int period = 24 * 60 * 60 * 1000;//执行间隔 if(myTask==null){ myTask = new MyTask(arg0.getServletContext()); timer.schedule(new MyTask(arg0.getServletContext()), date, period);   //timer.schedule(new CleanTpIpTask(arg0.getServletContext()), date);//只执行1次 //timer.schedule(new CleanTpIpTask(arg0.getServletContext()), 0, period);//项目启动立刻执行,每隔period 毫秒执行1次 } } }

3.在web.xml中配置

  webservice.MyTaskListener

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Javaweb 定时器功能代码实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Javaweb 定时器功能代码实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址