关于java 中的定时器

时间:2022-08-17 13:17:17

       定时器Timer  这个非常好用、在c语言中 用到的比较多,今天我就举一个我在工作中用到的例子吧,先说一下我的需求。

      我的需求是,我的客户端给服务器端发送数据,点击一次发送以后,会先发送一条数据,服务器接收到数据以后返回我一个标志位代表接收完成,然后我在发另一条数据,服务器再返回,这样一直发送(自定义发送几次)如果服务器没有返回那么我就不发送,提示发送信息失败。

    面对这样的需求我遇到了几个问题,①如何做到发送以后要等服务器返回我才能发送第二条,②如果服务器没有返回我如何设置超时

     我也是一个新手,查了好长时间的资料总是处理不好这些问题,最后还是用到了定时器很好的解决了我的问题,不说了直接上代码

   我做的事android 程序,首先开进入主界面我会执行time()这个方法

private void time() {
Timer time = new Timer();
time.scheduleAtFixedRate(task, 100, 100);// 延时100毫秒、100毫秒执行一次,不断执行
g_iWebRecTimeOutCnt = 0;
}

调用这个方法,会在进入主界面就开启定时器,当满足定时器的条件就会进入task,在这个time中我给他了一个全局的int 变量g_iWebRecTimeOutCnt 给他赋值为0,

然后创建了TimerTask 这个任务

private TimerTask task = new TimerTask() {// 由 Timer 安排为一次执行或重复执行的任务。

@Override
public void run() {
if (g_iWebRecTimeOutCnt > 0) {
g_iWebRecTimeOutCnt -= 1;
}


}
};

在这个任务中设定了 当变量g_iWebRecTimeOutCnt >0的时候会让他0.1秒-1一次直到归0;

现在定时器设置好了,下面开始用到定时器

builder.setPositiveButton("上传", 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("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.create().show();

呵呵这个我的一个上传按钮,点击上传显示一个dialog“正在上传”     开启一个线程去做上传的操作

Runnable sendNable = new Runnable() {

public void run() {//上传的线程

count = xxx;//count是一个int的id
try {
if (WebSendSingleMemberData(count)) {//这个是我封装的上传一个构件的方法
// 发送成功,开始判断是否有现场信息
g_bSendError = false;//这是一个布尔的变量true表示 上传失败  false 表示上传成功

if (WebSendSingleSiteData(pictureID)) {
// 如果现场信息发送成功,开始判断是够有图片信息
g_bSendError = false;
picList = db
.selectAllPictureInfo1(pictureID);
if (picList.size() > 0) {
pictureID = "";
for (int i = 0; i < picList.size(); i++) {


if (webSendSinglePicData(i)) {
// 代表该图片发送成功
g_bSendError = false;
} else {
// 代表strGoujian下的第i张图片发送失败
g_bSendError = true;

}


}


}
} else {
// 发送不成功,发送失败strGoujian下的现场信息发送失败
g_bSendError = true;

}


}
} else {
// 发送不成功,提示构件信息发送失败count
g_bSendError = true;



}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}
if (!g_bSendError) {//如果是false 表示成功
Message msgSuc = new Message();
msgSuc.what = 6;
mHandler.sendMessage(msgSuc);
} else {否则  表示失败
Message msgerror = new Message();
msgerror.what = 7;
mHandler.sendMessage(msgerror);
}

}
};


上面主要是我的一个逻辑,只有一个发送成功才发送另一个,下面开始用到定时器

// 发送一个构件信息的方法
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);//初始化协议头,大家用不到
try {
bWebRecValid = sendMsg(buffer, cont);//这个方法是发送的,发送文本信息都用这个方法
} catch (InterruptedException e) {


e.printStackTrace();
}
return bWebRecValid;
}



//发送文本信息的封装的方法

// 发送数据的方法
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);//这个是发送协议头
char[] bCont = cont.toCharArray();
writer.write(bCont);//这个是发送数据
writer.flush();


int iAllRecBytes;
int iRecByte;
byte AllRecBuff[] = new byte[1024];
byte RecBuff[] = new byte[1024];


iAllRecBytes = 0;
g_iWebRecTimeOutCnt = 50; // 0.1秒 定时器     !!!! 在这里给定时器设置成50,  50>0   就会进入定时器0.1秒去-1,知道归0,只要是在这5秒钟内服务器有数据返回下面都可以接受


while (g_iWebRecTimeOutCnt > 0) { // 等待 5秒超时
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[224];
ret[1] = RecBuff[225];
ret[2] = RecBuff[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) {
// 5秒接收超时, 提示超时对话框,并退出!!!!!  如果5秒钟已过,那么定时器就归0了, 就不能在进入上面的接收了  会在这里设置bWebRecValid =false 表示发送失败


bWebRecValid = false;
}


return bWebRecValid;


} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bWebRecValid;
}



好吧这就是我程序中的定时器的用法,本来打算分离出来的,不过分离出来 简单的一个定时器   比较抽象,所以还是把自己项目中用法贴出来了,好好读,你会有所收获的!