我编写了一个java socket服务器程序,它连续监听端口。它为传入数据创建一个新的文本文件,但我想每隔30分钟创建一个新的文本文件。
有人可以帮我安排每30分钟一次吗?
谢谢。
@paul:我有以下代码:
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);
}
}
}
在“timer.scheduleAtFixedRate(new TimerTask()”这行中它给出了以下错误:[找不到scheduleAtFixedRate()的合适方法 方法java.util.Timer.scheduleAtFixedRate(java.util.TimerTask,java.util.Date,long)不适用 (实际和正式的参数列表长度不同) 方法java.util.Timer.scheduleAtFixedRate(java.util.TimerTask,long,long)不适用 (实际和正式的参数列表长度不同)]
at“line = is.readLine();”它给了我以下错误:[无法为最终变量行赋值]。
我是java的新手。我很遗憾这个可怕的缩进。请帮帮我。
答案 0 :(得分:5)
您的服务器只需创建一个每30分钟触发一次的定时间隔并创建该文件。 See here for an example,Java docs和another example。
这是代码片段,其中包含一些针对您情况的mod:
int delay = 0; // delay for - no delay
int period = 1800000; // repeat every 1.8 mil milliseconds = 30 minutes
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Create file here
}
}, delay, period);
修正了代码:
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 {
public static void main(String args[]) {
new Runner().go();
}
}
class Runner {
public static LinkedList<String> data = new LinkedList<String>();
public void go() {
ServerSocket echoServer = null;
MyTimerTask timerTask = new MyTimerTask();
new Timer().scheduleAtFixedRate(timerTask, 0, 2000);
try {
echoServer = new ServerSocket(3000);
}
catch (IOException e) {
System.out.println(e);
}
try {
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true) {
String line = is.readLine();
data.add(line);
os.println("From server: "+ line);
System.out.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
class MyTimerTask extends TimerTask {
public void run() {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-hhmm");
String line = null;
System.out.print(".");
try {
String str = format.format(new Date());
FileWriter fstream = new FileWriter("C://" +str+".txt",true);
BufferedWriter out = new BufferedWriter(fstream);
while (Runner.data.size() > 0) out.write(Runner.data.getLast());
out.newLine();
out.flush();
out.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage() + e.getStackTrace()[0].toString());
}
}
}
答案 1 :(得分:2)
如果在Windows上,请创建使用Windows计划程序安排的批处理文件。如果在unix / linux中,你用cron安排的bash脚本。这将是最简单和最可靠的,因为操作系统将完成所有工作。
答案 2 :(得分:1)
有很多方法可以做到这一点。为了获得更大的灵活性,我会看一下Quartz-Scheduler
答案 3 :(得分:1)
可以选择线程安排。 如果您阅读线程文档。它提到它不保证在调用时调用线程,但它将被放入队列中。这仍然是可取的。
请勿使用操作系统级别的计划应用 从OS调用批处理应用程序会失去通过应用程序配置设置的灵活性。对于java程序员来说,这将是最糟糕的方法
最佳Quartz-Scheduler 最佳方法将由Gevorg使用Quartz-Scheduler
提及答案 4 :(得分:0)
您可以尝试将其用于基本调度目的。对于高级计划,您可以使用Quartz库。
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NTHREADS);
ScheduledFuture<?> result = scheduler.scheduleWithFixedDelay(
Runnable, 0, 1800, TimeUnit.SECONDS);
0是初始延迟,1800是任务应该运行的后续时间段。
答案 5 :(得分:-2)
/* File Signature.java created by Daniel Hicks on Mon Jun 11 2001. */
import java.io.*;
import java.util.*;
public class Signature {
public static void main(String args[]) throws Exception {
ResourceBundle properties = ResourceBundle.getBundle("WebSignature");
String sigName = properties.getString("sig.file");
String protoName = properties.getString("proto.file");
String sayingsList = properties.getString("sayings.list");
long waitTime = Long.parseLong(properties.getString("delay.time"));
int lineLength = Integer.parseInt(properties.getString("line.length"));
long notFoundTime = Long.parseLong(properties.getString("file.not.found.time"));
int notFoundRetries = Integer.parseInt(properties.getString("file.not.found.retries"));
Vector proto = new Vector();
BufferedReader protoReader = new BufferedReader(new FileReader(protoName));
String protoLine = protoReader.readLine();
while (protoLine != null) {
proto.addElement(protoLine);
protoLine = protoReader.readLine();
}
protoReader.close();
Vector sayings = new Vector();
BufferedReader sayingsReader = new BufferedReader(new FileReader(sayingsList));
String sayingsLine = sayingsReader.readLine();
while (sayingsLine != null) {
sayings.addElement(sayingsLine);
sayingsLine = sayingsReader.readLine();
}
sayingsReader.close();
Random rand = new Random();
int retryCount = notFoundRetries; // Require first cycle to work
while (true) {
int randVal = rand.nextInt();
randVal = Math.abs(randVal) % sayings.size();
try {
PrintWriter sigWriter = new PrintWriter(new FileWriter(sigName));
for (int i = 0; i < proto.size(); i++) {
sigWriter.println(proto.elementAt(i));
}
putSaying(sigWriter, (String) (sayings.elementAt(randVal)), lineLength);
sigWriter.close();
retryCount = 0;
}
// Catch I/O error due to AFS being offline.
catch (java.io.FileNotFoundException ex) {
retryCount++;
if (retryCount > notFoundRetries) {
throw ex;
}
// Sleep for a long time (eg, 30 minutes).
Thread.sleep(notFoundTime);
}
Thread.sleep(waitTime);
}
}
private static void putSaying(PrintWriter sigWriter, String saying, int lineLength) throws Exception {
saying = saying.trim();
java.text.BreakIterator lineIterator = java.text.BreakIterator.getLineInstance();
lineIterator.setText(saying);
int pos = 0;
int last = lineIterator.last();
while (pos < last) {
int newPos = pos + lineLength;
if (newPos >= last) {
newPos = last;
}
else {
newPos = lineIterator.preceding(newPos);
if (newPos <= pos) {
newPos = lineIterator.following(pos);
}
}
sigWriter.println(saying.substring(pos, newPos));
pos = newPos;
while ((pos < saying.length() - 1) && Character.isWhitespace(saying.charAt(pos))) {
pos++;
}
}
}
}