Implementation and source code of timer Timer class in Java

Source: Internet
Author: User
Tags call back

In Windows programming, you can call settimer to install the timer in the specified window. The timer can periodically call back the user-specified method at the specified interval to execute periodic tasks, to cancel a timer, call killtimer to cancel the timer. But this type does not exist in the java standard package. The class package described below can implement the above functions.

The following is an interface, which must be implemented by a class that supports the timer function:

Timerclient. Java

Package com. ly. util;

/**
* Timerclient Interface
*
* @ Version 1.0, 8 October 1995
*
*/
Public interface timerclient
{
Void timerevent (int id );
}

 

The lower layer is the implementation of the timer, which includes three classes: timerctl, timertask, and timertasks. Timertask is used to describe timer information. Timertasks is a list of timertasks, so that we can install multiple timers in an application at the same time. Timerctl is a timer control class and a thread. It constantly checks whether timertask has expired. If timertask has reached the specified time, it calls back the timerevent interface of timerclient specified by timertask.

Timerctl. Java

Package com. ly. util;

Import java. util. vector;
Import java. util. enumeration;
// Import com. Borland. JB. util. Diagnostic;

/**
* Timer component
*
* Note:
*-The successful operation of this timer requires clients to execute simple, short
* Code snippets when called back by the engine. Otherwise the queue's delivery
* Mechanic will be held up
*
* Further work:
*-When thread. Interrupt is implemented we can switch from the busy wait model
* The calculated wait model. Without the interrupt the thread waits for
* Calculated interval before waking up. This is a problem if another shorter
* Request arrives. For now we'll assume the minimum resolution of the timer is
* 100 ms.
*
* @ Version 1.0, 2 October 1995
*
*/
Public class timerctl
{
Static timertasks;

Public timerctl (){
}

/*
* Start a timer running
*/
Public static void starttimer (timerclient client, int eventid, long delay, Boolean repeat ){
// Create the timer if necessary
If (timertasks = NULL ){
Timertasks = new timertasks ();
Timertasks. Start ();
}

// Diagnostic. Out. println ("Timer: starttimer" + eventid );

// Add the new task to the queue
Timertasks. Add (client, eventid, delay, repeat );
}

/*
* Stop a timer
*/
Public static void stoptimer (timerclient Client client, int eventid ){
// Diagnostic. Out. println ("Timer: stoptimer" + eventid );
If (timertasks! = NULL)
Timertasks. End (client, eventid );
}
}

Class timertasks extends thread
{
Vector tasks = new vector ();
Boolean suincluded = false;
Boolean sleeping = false;

/**
* Thread task runner
*/
Public void run (){
// Loop forever
While (true ){
Long sleeptime = 0;

// Ensure that the tasks class is protected
Synchronized (tasks ){
// Diagnostic. Out. println ("Timer: tick ");

// Scan the job list for any jobs which may fire.
// Mark one-shot jobs for deletion
// Calculate the maximum time we can sleep
Sleeptime = scan ();

// Delete deletepending jobs. deletepending jobs result from one-shots which have
// Been sent, and repeat jobs which have been canceled. Jobs may have been
// Canceled during the scan process.
Purge ();
}

// Suspend timer if necessary
If (tasks. Size () = 0 ){
// Diagnostic. Out. println ("Timer: Suspend ");
Try {
Synchronized (this ){
Suincluded = true;
Wait ();
}
}
Catch (interruptedexception e ){
}
}
Else {
// Diagnostic. Out. println ("Timer: Suggested sleeping for" + sleeptime );
If (sleeptime> = 0 ){
Try {
Sleeping = true;
Sleep (sleeptime );
Sleeptime = scan ();
Sleeping = false;
}
Catch (interruptedexception I ){
// Diagnostic. Out. println ("Timer: Caught me napping ");
}
}
}
}
}

/**
* Add a new task
*/
Public void add (timerclient client, int eventid, long delay, Boolean repeat ){
Timertask T = new timertask (client, eventid, delay, repeat );

Synchronized (tasks ){
Tasks. addelement (object) t );
}

// Want instant response-Wake the thread if it's napping
// Unfortunately the interrupt () method is not working
// If (sleeping)
// Interrupt ();

If (suincluded ){
Synchronized (this ){
Notify ();
// Diagnostic. Out. println ("Timer: Resume ");
Suincluded = false;
}
}
}

/**
* Find the job and mark it for deletion
*/
Public void end (timerclient client, int eventid ){
Synchronized (tasks ){
For (INT I = 0; I <tasks. Size (); I ++ ){
Timertask t = (timertask) tasks. elementat (I );

// If (! T. deletepending & T. Client = client & T. eventid = eventid)
If (T. deletepending = false & T. Client = client & T. eventid = eventid ){
// JPBS-if we don't reset 'repeat', deletepending will be set again
T. Repeat = false;
T. deletepending = true;
Break;
}
}
}
}

/**
* Clear out all the dead wood
*/
Void purge (){
For (INT I = 0; I <tasks. Size (); I ++ ){
Timertask t = (timertask) tasks. elementat (I );

If (T. deletepending ){
// Diagnostic. Out. println ("Timer: purged ");

Tasks. removeelementat (I );
I --;
}
}
}

Long scan (){
// The value added to the current time determines the Max time
// The next scan
// This is 100 now since thread. Interrupt () is not implemented
Long nexttime = system. currenttimemillis () + 100;

For (INT I = 0; I <tasks. Size (); I ++ ){
Timertask t = (timertask) tasks. elementat (I );

// If not already deletepending, test (and possibly send the event)
// As a result, the job may be flagged for deletion.
// May also be a non-repeating job and so require self Deletion
If (! T. deletepending)
T. Test ();

// If the task didn't get deleted-see what it contributes to the time
If (! T. deletepending)
Nexttime = math. Min (nexttime, T. timenext );

// Diagnostic. Out. println ("Timer: scanning" + T. eventid + "" + (T. deletepending = true? "Del ":""));
}

Return nexttime-system. currenttimemillis ();
}
}

Class timertask
{
Timerclient client;
Int eventid;

Long timeprev;
Long timedelay;
Long timenext;

Boolean repeat;
Boolean deletepending;

Public timertask (timerclient client, int eventid, long timedelay, Boolean repeat ){
This. Client = client;
This. eventid = eventid;
This. timedelay = timedelay;
This. Repeat = repeat;

// Schedule the next click-now + Delay
Timenext = system. currenttimemillis () + timedelay;
Deletepending = false;

// Diagnostic. Out. println ("Timer: adding new task ");
}

Public void test (){
If (system. currenttimemillis ()> = timenext ){
// Diagnostic. Out. println ("Timer: Fire ");

// Fire the event
Client. timerevent (eventid );

// Update the next time
Timenext = system. currenttimemillis () + timedelay;

Deletepending =! Repeat;
}
}
}

 

 
The following is an example

Timertest. Java

Package com. ly. util;

Import java. Io .*;
Import java. util .*;
Import com. ly. util .*;

/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company: http://dozb.blogchina.com
* @ Author dozb
* @ Version 1.0
*/
Public class timertest implements timerclient {
Public timertest ()
{
Starttime ();
}
Public void timerevent (int id)
{
System. Out. println ("timerevent ...");
}
Public void starttime ()
{
Timerctl. starttimer (this, 1000 *, true );
}
Public void stoptime ()
{
Timerctl. stoptimer (this, 1 );
}

Public static void main (string [] ARGs)
{
New timertest ();
Try
{
Thread. Sleep (200000 );
} Catch (exception E)
{
}

}
}

 

In this way, you can use socket communication efficiently. It is a solution before the asynchronous socket version is released. :)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.