I have written a java socket server program which listens to a port continuously. It creates a new text file for the incoming data but I want to create a new text file every 30 mins.
Can someone help me with scheduling this to run every 30 mins?
Thank you.
@paul: i have the following code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.util.Timer;
import java.util.TimerTask;
public class DateServer extends Thread {
static public String str;
public static void main(String args[]) {
String pattern = "yyyyMMdd-hhmm";
SimpleDateFormat format = new SimpleDateFormat (pattern);
str = format.format(new Date());
int delay = 0;
int period = 180000;
Timer timer = new Timer();
ServerSocket echoServer = null;
String line = null;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
try {
echoServer = new ServerSocket(3000);
}
catch (IOException e) {
System.out.println(e);
}
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
while (true) {
line = is.readLine();
os.println("From server: "+ line);
System.out.println(line);
timer.scheduleAtFixedRate(new TimerTask() {
public void run(){
try{
FileWriter fstream = new FileWriter("C://" +str+".txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(line);
out.newLine();
out.flush();
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}}, delay, period);
}
catch (IOException e) {
System.out.println(e);
}
}
}
-
At
timer.scheduleAtFixedRate(new TimerTask()this line it is giving me the following error:[no suitable method found for scheduleAtFixedRate()
method java.util.Timer.scheduleAtFixedRate(java.util.TimerTask,java.util.Date,long) is not applicable
(actual and formal argument lists differ in length)
method java.util.Timer.scheduleAtFixedRate(java.util.TimerTask,long,long) is not applicable
(actual and formal argument lists differ in length)] -
at
line = is.readLine();it is giving me the following error:[cannot assign a value to final variable line].
I am new to java. i am sorry for the terrible indentation. please help me.
Your server simply needs to create a timed interval that fires off every thirty minutes and creates the file. See here for an example, the Java docs and another example.
Here’s the code snippet with a few mods for your situation:
And fixed up code: