开发者

Schedule a java program

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);

       开发者_JS百科      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);
    }        
    }
}
  1. 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)]

  2. 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:

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);

And fixed up 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 {
    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());
        }
    }
}


If on windows, create a batch file that you schedule with the windows scheduler. If in unix/linux, a bash script that you schedule with cron. This would be the easiest and most reliable as the OS would be doing all the work.


There are many many way to do this. For more flexibility I would look at Quartz-Scheduler


It is okay to go for thread scheduling. If you read documentation of threads. It mentions that it doesn't guarantee that thread would be invoked when called, but it will be put into the queue. Still this will be preferable.

Don't go for schedule app in OS level Calling a batch app from OS looses your flexibility to configure the setting through application. It will be worst approach for a java programmer

Best Quartz-Scheduler The best approach will be as mentioned by Gevorg using Quartz-Scheduler


You can try this for basic scheduling purposes. For advanced scheduling you can use Quartz library.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NTHREADS);
ScheduledFuture<?> result = scheduler.scheduleWithFixedDelay(
                                 Runnable, 0, 1800, TimeUnit.SECONDS);

0 is the initial delay, 1800 is the subsequent period at which the task should run.


/* 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++;
        }
    }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜