一个简朴的Timer Service
当前位置:以往代写 > JAVA 教程 >一个简朴的Timer Service
2019-06-14

一个简朴的Timer Service

一个简朴的Timer Service

副标题#e#

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


#p#副标题#e#

启动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,所以本身写的,假如各人有雷同的代码,可以提出来参考参考,感谢

    关键字:

在线提交作业