java 和 web socket 中的 TimerTask
我正在尝试使用 Java 的 DatagramSocket 和 DatagramPacket 类编写一个基本的客户端服务器。我已经设置了基本代码,但我想要一种定期从客户端向服务器发送 100 条消息的方法,即 1 秒、2 秒或 5 秒。
基本上,我想要这样的东西:
while (count != 0)
sleep (1);
create message packet;
send message packet;
count--;
在C中有一个sleep方法,但我不知道如何在java中做到这一点。有人有什么建议吗?
I'm trying to write a basic client server using Java's DatagramSocket
and DatagramPacket
classes. I have the basic code set up, but I want a way to send 100 messages from my Client to my Server at regular intervals i.e. 1 sec, or 2 sec, or 5 sec.
Basically, I want something like:
while (count != 0)
sleep (1);
create message packet;
send message packet;
count--;
In C there's a sleep method, but I'm not sure how to do that in java. Anyone have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您始终可以调用 Thread.sleep(),它很大程度上相当于 C 中的 sleep 函数。但我会推荐一种替代方法来完成您的程序。看一下 ScheduledThreadPoolExecutor 类,它允许您安排一段代码定期运行:
You can always call
Thread.sleep()
, which is largely equivalent to thesleep
function from C. But I would recommend an alternative route to accomplishing your program. Take a look at the ScheduledThreadPoolExecutor class, it allows you to schedule a piece of code to be run at regular intervals:这是任务类的代码
Here is the code for Task class
Java 比 C 水平相当高。(当然你也有 C 中的线程库:),我的意思是这是作为 Java 语言支持而不是库来支持的)
所以,你可以使用 Timer 类。
来到主要功能,您将
在该类中实现类似 TimerTask 的内容。
必须重写那里的运行方法。
Java is pretty high level than C. (of course you have thread libs in C too :), what I meant this is supported as Java language support than libraries)
So, you can use
Timer
class.Coming to the main functionality you will have something like
In that class implementing TimerTask.
Have to override a run method there.