Web-timeservice is used for timed invocation (triggering) applications, EJB2.1 also provides timerservice, but some application servers are not supported and some do not use EJBS at all. So I wrote a simple 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 ();
}
}
//contains multiple timerjob, and every time it is taken out to see if the call
public class Timerschedule extends TimerTask
{
Private 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 ();
}
}
}
/**
* Compare whether two time difference is less than TIMERSERVICE.P (one cycle)
* @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;
}
}
//This interface describes how to complete the timertask, please refer to timerjobexample
Interface Timerjob
{
public void execute ();
public Date getnextexedate ();
}
/**
* This example is used to demonstrate how to complete the Tiemrjob
* This example function is called at one o'clock in the morning every day of the
*/
public class Timerjobexample implements Timerjob
{
Calendar nextdate = null;
public timerjobexample ()
{
nextdate = Calendar.getinstance ();
Nextdate.add (calendar.day_of_month,1);
//will set the call time is (the next day) every 1 o'clock in the morning
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 ());
}
}