服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个简单的timer service


  web-timeservice用于定时调用(触发)应用,ejb2.1也提供了timerservice,但现在有的application server不支持,有的就根本没有用到ejb,所以我写了一个简单的timerserivce

public class timerservice
{
 public static final long p = 1000*60*60;
  timer timer = new timer(false);
  timerschedule schedule = null;
 public timerservice()
 {
 }

 public void start() throws exception
 {
  schedule = new timerschedule();
  schedule.addtimerjob(new sometimerjob());
  //add other job here
  timer.schedule(schedule,0,p);
 }

 public void stop() throws exception
 {
  timer.cancel();
 }
}

//包含了多个timerjob,并每到一定时候取出来看看是否该调用
public class timerschedule extends timertask
{
 private list list = new arraylist();
 public timerschedule()
 {}
 public void addtimerjob(timerjob job)
 {
  list.add(job);
 }

 public void run()
 {
  date now = calendar.getinstance().gettime();
  date next = null;
  for(int i=0;i<list.size();i++)
  {
   timerjob job = (timerjob)list.get(i);
   next = job.getnextexedate();
   if(isequals(now,next))
   {
    job.execute();
   }
  }
 }

/**
* 比较俩个时间相差是否小于timerservice.p(一个周期)
* @param now
* @param next
* @return
*/
private boolean isequals(date now,date next)
{
 long time = next.gettime()-now.gettime();
 if (time <= timerservice.p && time >= 0)
 {
  return true;
 }
 else
 {
  return false;
 }
}

public boolean cancel()
{
 return true;
}
}


//该接口描述了如何完成timertask,请参考timerjobexample
interface timerjob
{
 public void execute();
 public date getnextexedate();
}

/**
* 该例子用于演示如何完成tiemrjob
* 该例子功能是在每天的凌晨一点调用
*/
public class timerjobexample implements timerjob
{
 calendar nextdate = null;
 public timerjobexample()
 {
  nextdate = calendar.getinstance();
  nextdate.add(calendar.day_of_month,1);
  //将设置调用时间是(第二天的)每天凌晨1点
  nextdate.set(calendar.hour_of_day,1);
 }
 public void execute()
 {
  nextdate.add(calendar.day_of_month,1);
  nextdate.set(calendar.hour_of_day,1);
  callfunction();
 }

 public date getnextexedate()
 { 
  return nextdate.gettime();
 }

 private void callfunction()
 {
  system.out.println("timerjobexample call ejb funcation:"+new date());
 }
}

  启动web_timerservice

  启动web-timerservice可以有多种方法,下面列出一个简单的方法,通过jsp来启动,停止timerservice

<%@ page contenttype="text/html; charset=gbk" %>
<%@ page import="com.ted.cfioms.common.alert.*"%>
<%
 timerservice service = (timerservice)application.getattribute("timerservice");
 boolean isstart = true;
 if(service == null)
 {
  service = new timerservice();
  application.setattribute("timerservice",service);
  service.start();
 }
 else
 {
  service.stop();
  isstart = false;
  service = null;
 }
%>
<html>
<head>
 <title>
  timerservice
 </title>
</head>
<body bgcolor="#ffffff">
<h1>
 <%=(isstart?"start ok":"stop ok")%>
</h1>
</body>
</html>

  简单吧,呵呵,我在网上没找到合适的timerservice,所以自己写的,如果大家有类似的代码,可以提出来参考参考,谢谢

扫描关注微信公众号