1. 定时向文档传输数据:
package project2;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
public class MyTimeTask02 {
public static void main(String[] args) throws Exception {
FileWriter f = new FileWriter("F:/test/111.txt");
Timer t = new Timer();
MyTimeTaskDemo task= new MyTimeTaskDemo(f);
t.scheduleAtFixedRate(task,new Date(), 3000);
}
}
package project2;
import java.io.FileWriter;
import java.io.IOException;
import java.util.TimerTask;
public class MyTimeTaskDemo extends TimerTask {
FileWriter f ;
public MyTimeTaskDemo(FileWriter f) {
this.f = f;
}
public void run() {
try {
f.write("zaizai");
f.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2 定时给客户端发送数据
package project;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class MyReceiveDemo {
public static void main(String[] args) throws IOException {
//创建一个收货快递员!
DatagramSocket ds = new DatagramSocket(10089);
while(true){
//快递员创建一个数据包以便接收数据!
byte[] buf =new byte[1024];
int length = buf.length;
DatagramPacket dp = new DatagramPacket(buf, length);
//快递员接收包裹!
ds.receive(dp);
//快递员确认包裹的ip
InetAddress address = dp.getAddress();
String ip = address.getHostAddress();
//快递员拆开包裹显示数据!
byte[] bufs = dp.getData();
int lengths = dp.getLength();
String s = new String (bufs,0,lengths);
System.out.println(ip+"----"+s);
}
}
}
package cn.mashen.timetask;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
// 快递员将数据打包!
DatagramSocket ds;
public MyTimerTask(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
byte[] buf = "shengzai".getBytes();
int length = buf.length;
InetAddress address = null;
try {
address = InetAddress.getByName("192.168.11.44");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port = 10089;
DatagramPacket dp = new DatagramPacket(buf, length, address, port);
// 快递员发送数据包裹!
try {
ds.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package cn.mashen.timetask;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Date;
import java.util.Timer;
public class MainTimerTask {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
MyTimerTask task=new MyTimerTask(ds);
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, new Date(), 2000);
}
}