About the timer in Java

Source: Internet
Author: User
Tags sendmsg

The timer is very easy to use and is used in C language. Today I will give an example of what I have used in my work. Let's talk about my needs first.

My requirement is that my client sends data to the server. After one click, a piece of data will be sent first. After the server receives the data, it returns a flag indicating that the receiving is complete, then I am sending another piece of data, and the server will return it again. This will keep sending (custom sending several times). If the server does not return it, I will not send it, prompting that the sending information will fail.

In the face of such requirements, I encountered several problems. ① how can I send the second message after the server returns? ② how can I set timeout if the server does not return?

I am also a newbie. I have been checking the materials for a long time and can't solve these problems. At last, I used a timer to solve my problem. I did not say that I directly went to the code.

The android program that I am working on first opens the main interface and I will execute the time () method.

Private void time (){
Timer time = new timer ();
Time. scheduleatfixedrate (task, 100,100); // The latency is 100 milliseconds and 100 milliseconds.
G_iwebrectimeoutcnt = 0;
}

When this method is called, the timer is enabled on the main interface. When the timer conditions are met, the timer enters the task, in this time, I assigned him a global int variable g_iwebrectimeoutcnt with a value of 0,

Then the timertask task is created.

Private timertask task = new timertask () {// tasks scheduled by timer for one execution or repeated execution.

@ Override
Public void run (){
If (g_iwebrectimeoutcnt> 0 ){
G_iwebrectimeoutcnt-= 1;
}

}
};

In this task, it is set that when the variable g_iwebrectimeoutcnt is greater than 0, it will take 0.1 seconds to 1 until it is set to 0;

Now that the timer has been set, the timer will be used below

Builder. setpositivebutton ("Upload", new dialoginterface. onclicklistener (){
@ Suppresslint ("parsererror ")
Public void onclick (dialoginterface dialog, int whichbutton ){
Showdialogsend ();
Username = etusername. gettext (). tostring ();
Taskno = ettaskno. gettext (). tostring ();

Deleteidarray = new int [list. Size ()];
New thread (sendnable). Start ();

Dialog. Dismiss ();
}
});

Builder. setnegativebutton ("cancel", new dialoginterface. onclicklistener (){
Public void onclick (dialoginterface dialog, int whichbutton ){
Dialog. Dismiss ();
}
});
Builder. Create (). Show ();

This is one of my upload buttons. Click Upload to display a dialog "uploading" to enable a thread for upload operations.

Runnable sendnable = new runnable (){

Public void run () {// upload thread

Count = xxx; // count is an int ID.
Try {
If (websendsinglememberdata (count) {// This Is My encapsulated Method for uploading a component
// The message is sent successfully, and the system starts to determine whether there is any on-site information.
G_bsenderror = false; // This Is A boolean variable. "True" indicates that the upload fails. "false" indicates that the upload is successful.

If (websendsinglesitedata (pictureid )){
// If the on-site information is successfully sent, start to determine if there is sufficient Image Information
G_bsenderror = false;
Piclist = DB
. Selectallpictureinfo1 (pictureid );
If (piclist. Size ()> 0 ){
Pictureid = "";
For (INT I = 0; I <piclist. Size (); I ++ ){

If (websendsinglepicdata (I )){
// Indicates that the image is successfully sent.
G_bsenderror = false;
} Else {
// It indicates that the I-th image under strgoujian fails to be sent.
G_bsenderror = true;

}

}

}
} Else {
// Failed to send the field information in strgoujian
G_bsenderror = true;

}

}
} Else {
// Failed to send, prompting component information failed count
G_bsenderror = true;

}
} Catch (unsupportedencodingexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}

}
}
If (! G_bsenderror) {// if it is false, the operation is successful.
Message msgsuc = new message ();
Msgsuc. What = 6;
Mhandler. sendmessage (msgsuc );
} Else {otherwise, it indicates a failure.
Message msgerror = new message ();
Msgerror. What = 7;
Mhandler. sendmessage (msgerror );
}

}
};

The above is mainly one of my logic. Only one of them can be sent successfully. The timer is used below.

// Method for sending component information
Private Boolean websendsinglememberdata (INT idatabaseindex)
Throws unsupportedencodingexception {
Memberinfo mem = dB. selectmemberinfo (idatabaseindex );
Byte buffer [];
String cont = mem. getmembercnt ();

Strgoujian = mem. getmembername ();
Pictureid = mem. getpictureid ();
Sitstatus = mem. getsiteinfostatus ();
Length = getwordcount (cont) + 1;
Buffer = initprotocal (1, "", "", length, strgoujian, username, taskno); // initialize the protocol header.
Try {
Bwebrecvalid = sendmsg (buffer, cont); // This method is used to send text information.
} Catch (interruptedexception e ){

E. printstacktrace ();
}
Return bwebrecvalid;
}

// Encapsulate the sent text information

// Method for sending data
Private Boolean sendmsg (byte [] MSG, string cont)
Throws interruptedexception {

Try {
Out = socket. getoutputstream ();
OSW = new outputstreamwriter (socket. getoutputstream (), "GBK ");
In = socket. getinputstream ();
Writer = new bufferedwriter (OSW );

Out. Write (MSG); // This is the sending protocol header.

Char [] bcont = Cont. tochararray ();
Writer. Write (bcont); // This is to send data
Writer. Flush ();

Int iallrecbytes;
Int irecbyte;
Byte allrecbuff [] = new byte [1024];
Byte recbuff [] = new byte [1024];

Iallrecbytes = 0;
G_iwebrectimeoutcnt = 50; // 0.1 seconds timer !!!! Set the timer to 50, 50> 0, and the timer will go to-1 in 0.1 seconds. If the value is 0, the server will receive the following data within the 5 seconds.

While (g_iwebrectimeoutcnt> 0) {// wait for 5 seconds to time out
Recbuff = new byte [IN. Available ()];
Irecbyte = in. Read (recbuff );

If (irecbyte> 0 ){//
For (INT I = 0; I <irecbyte; I ++ ){
Allrecbuff [I + iallrecbytes] = recbuff [I];
}
Iallrecbytes + = irecbyte;

If (iallrecbytes = 732 ){
Byte [] ret = new byte [4];
RET [0] = recbuff [1, 224];
RET [1] = recbuff [225];
RET [2] = recbuff [1, 226];
RET [3] = recbuff [227];
N = toint (RET );
If (n> = 1) & (n <= 3 )){
// G_iwebrectimeoutcnt = 0;
Bwebrecvalid = true;
Break;
}
}
If (iallrecbytes> 732 ){
Bwebrecvalid = false;
Break;
}
}
}
If (g_iwebrectimeoutcnt = 0 ){
// Receive timeout in 5 seconds. The timeout dialog box is displayed, and exit !!!!! If the time has elapsed in five seconds, the timer will be set to 0, so you cannot enter the above Reception. bwebrecvalid = false will be set here to indicate that the sending fails.

Bwebrecvalid = false;
}

Return bwebrecvalid;

} Catch (unsupportedencodingexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return bwebrecvalid;
}

Well, this is the usage of the timer in my program. It was originally intended to be separated, but a simple timer was relatively abstract, So I posted the method in my project and read it well, you will get something!

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.