aspose file tools*
The moose likes Java in General and the fly likes Set Timer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Set Timer" Watch "Set Timer" New topic
Author

Set Timer

Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
Hi,
How to set Timer for 5 seconds in Java?
Plz let me know by example.
Thanks in advance,
Angela
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
Originally posted by Angela Jessi:
Hi,
How to set Timer for 5 seconds in Java without passing actionListener as as argument of Timer Method?
Plz let me know by example.
Thanks in advance,
Angela

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
I don't get what you would be doing if you don't tell the timer what class to call when the timer goes off.
If you just want to wait 5 seconds and continue, then use the Thread.wait(milliseconds) method.
Manfred.
Sri Bala
Ranch Hand

Joined: Mar 06, 2001
Posts: 63
That was close except the method is sleep() and not wait(). The arguments are sleep( milliseconds, nanoseconds ). Here's a program that waits for 5 secs.
public class Wait
{
public static void main( String args[] )
{
System.out.println("Sleeping ...");
try
{
Thread.sleep(5*1000);
}
catch(Exception ex)
{
}
System.out.println("Done");
}
}
Sri Bala
Ranch Hand

Joined: Mar 06, 2001
Posts: 63
Manfred,
When I look at wait(), it is a non-static member in Object and needs an instance of thread. Also there's a possibility of waking up before 5 seconds when some other thread on the same object calls notify() or notifyAll(). So it's not guaranteed to wait for 5 seconds and hence I suggest sleep().
Sri.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Yeah, my mistake.
Manfred.
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428

Thanks Manfred & Sri Bala,
I don't have thread class. On Client side, I have one API method, which is non-blocking in which i have set Timer for 5 sec, and i have to check if i get data from the server, if it is timeout & no data message from server, then i can return error message?

Also I want to know how to return error message in java

Thanks ,
Angela
Sri Bala
Ranch Hand

Joined: Mar 06, 2001
Posts: 63
I would like to see the part of your code to understand more about your problem.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Angela, what do you mean "I dont have thread class"? Even if you don't declare any of your own threads, the system itself always has at least one, which runs "main". Thread.sleep() is a static method, so it can be called from anywhere, and will sleep the current (in your case, the default, system) thread.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
Thanks Sri Bala And Frank.
Here is my one of subclasses code :
public class K_Socket extends Thread implements ActionListener
{
private Socket localSocket;
private Socket sclient;
private BufferedReader in;
private BufferedReader demarsh;
private PrintWriter out;
private Socket clientSocket;
private String mesg;
private StringBuffer buf;
private StringBuffer sendBuffer;
private int setTime = 5000;
protected K_Main main;
protected K_Marshall kmar;
int port,tmp1,maxbuf,read,temp;
int bytesend = 0;
char [] buffer;
char [] mBuffer;
Timer timer;
// constructor
public K_Socket(K_Main Main)
{
port = 9999;
bytesend = 0;
maxbuf = 2000;
tmp1 = 0;
temp = 0;
buffer = new char[maxbuf];
mBuffer = new char[2000];
sendBuffer = new StringBuffer(2000);
timer = new Timer(setTime,this);
buf = new StringBuffer(2000);
main = Main;
kmar = (K_Marshall)main.getObjects(1);
}
//open the socket to remote host
public void open(String ipAddr)
{
try
{
localSocket = new Socket(ipAddr , port);
System.out.println("The Host IP address is:" + localSocket.getInetAddress());
out = new PrintWriter(localSocket.getOutputStream());
}
catch(UnknownHostException uhe)
{
System.out.println("The Host is Unknown");
}
catch(IOException ioe)
{
System.out.println("I/O Error");
}
}
//To send the data to the server
public void send()
{
out.println(sendBuffer);
out.flush();
System.out.println("Marshall message sent to server:" + sendBuffer);
bufferCleanUp();
}
//To receive the data from the server
public void receive()
{
try
{
in = new BufferedReader(new InputStreamReader(localSocket.getInputStream()));
// loop to read data from server
while( (tmp1 = in.read(buffer, 0, 2000)) >= 0 )
{
System.out.println("current bytereceive:" + tmp1);
if( tmp1 < 0 )<br /> {<br /> System.out.println("Can not have a negative string");<br /> return;<br /> }<br /> main.addData(buffer , tmp1);<br /> }<br /> }<br /> catch(IOException e)<br /> {<br /> System.out.println("Reading Error");<br /> }<br /> }<br /> public int returnData()<br /> {<br /> timer.start();<br /> buf.append(mBuffer , 0 , temp);<br /> mesg = buf.toString();<br /> kmar.deMarshall(mesg);<br /> return 1;<br /> }<br /> //to return the buffer to store marshall data<br /> public StringBuffer getSendBlk()<br /> {<br /> return sendBuffer;<br /> }<br /> //to cleanup the buffer<br /> public int bufferCleanUp()<br /> {<br /> sendBuffer.setLength(0);<br /> return 1;<br /> }<br /> //check to see whether any message or not at specific interval<br /> public void actionPerformed(ActionEvent evt)<br /> {<br /> try<br /> {<br /> demarsh = new BufferedReader(new InputStreamReader(localSocket.getInputStream( )));<br /> if( (temp = in.read(mBuffer, 0, 2000)) >= 0 )
{
System.out.println("The Demarshall from Server!");
}
else
{
System.out.println("No Response from the Server!");
}
}
catch(IOException me)
{
System.out.println("Reading Demarshall Error");
}
timer.stop();
System.out.println("Time out!");
}
// to close the socket
public void close()
{
try
{
localSocket.close();
}
catch(IOException ie)
{
System.out.println("Error Closing Socket");
}
}
public void run()
{
receive();
System.out.println("Run RECEIVE() again!");
}
}
I have used Timer. Thread is continuously run to listen data from the server. So I used Timer, b'cos i can't use Thread.sleep() as thread is continuously running.
Question: The use of Timer is appropriate?
Plz let me know
Thanks again,
Angela
Sri Bala
Ranch Hand

Joined: Mar 06, 2001
Posts: 63
I haven't used Timer class. I looked up Timer and your code. It looks fine. There should be some bug somewhere else. I doubt if the use of Timer is appropriate in this case. actionPerformed is going to be called for any other events in addition to Timer. I would thread and sleep instead. Here's a simple example of thread and sleep. It keeps printing Hello until you press the enter key. The sleep method is a static and puts the currently executing thread to sleep.
import java.io.*;
public class MyThread implements Runnable
{
public void setDone() { done = true; }
boolean done = false;
public void run()
{
while(!done)
{
System.out.println("Hello");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
public static void main( String args[] )
{
BufferedReader bris = null;
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
bris = new BufferedReader(new InputStreamReader(System.in));
try {
bris.readLine();
myThread.setDone();
}
catch(Exception e)
{
e.printStackTrace();
}

}
paul edwards
Greenhorn

Joined: Mar 12, 2001
Posts: 6
I looked up some stuff on timers earlier today. Here is some code using a five second timer :
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder(5);
System.out.println("Task scheduled.");
}
}

Happy Trails!
Paul
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
Thanks Paul,
Graeme Brown
Ranch Hand

Joined: Oct 13, 2000
Posts: 193
Angela
I haven't looked at your code in detail, but it looks to me that thread waiting is better than a Timer. By setting your thread to wait it can be notified if data arrives from the server before the five second timer expires rather than having to explicitly wait for the full five seconds. You can set a timeout on the wait method and return your error message if the timeout expires.
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
Thanks Graeme,
I appreciate your help. I want to ask here very silly question:
How to return error message in java. Plz explain me by very simple example.
Thanks,
Angela
ryan burgdorfer
Ranch Hand

Joined: Jan 24, 2001
Posts: 219
You can generate an exception anywhere you want to, by simply stating:
throw new Exception( "Put your error message here" ) ;
Just put that line in an if/else clause (or however you want to conditionally generate the error) and call the method that contains the above line in a try/catch block.
------------------
  • Ryan Burgdorfer
  • Java Acolyte in
  • Columbus, OH USA


<UL TYPE=SQUARE><I><LI>Ryan Burgdorfer<BR><LI>Java Acolyte</I></UL>
 
 
subject: Set Timer