关于上述主题的一个快速问题。基本上,我正在编写一块软件,它从网络捕获数据并将其写入外部文件以进行进一步处理。

我想知道的是什么代码是最好的用途,以便获得这种所需效果。

感谢您的时间

David

有帮助吗?

解决方案

I'd probably implement it using a TimerTask. E.g.,

int hour = 1000*60*60;
int delay = 0;
Timer t = new Timer();

t.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        // Write to disk ...
    }
}, delay, hour);

Otherwise quarts is a powerful java scheduler which is capable of handling more advanced scheduling needs.

其他提示

You can use the Executor Framework, here is a sample implementation:

final List<String> myData = new ArrayList<String>();
final File f = new File("some/file.txt");

final Runnable saveListToFileJob = new Runnable(){

    @Override
    public void run(){ /* this uses Guava */
        try{
            Files.write(
                Joiner.on('\n').join(myData),
                f, Charsets.UTF_8);
        } catch(final IOException e){
            throw new IllegalStateException(e);
        }

    }
};
Executors
    .newScheduledThreadPool(1) /* one thread should be enough */
    .scheduleAtFixedRate(saveListToFileJob,
        1000 * 60 /* 1 minute initial delay */,
        1, TimeUnit.MINUTES /* run once every minute */);

The question probably needs a few more details. What part of the solution is causing you trouble?

  • The scheduling?
  • The reading from the network?
  • The persistence in a memory data structure?
  • The writing to a file?

You should also describe the problem domain a little bit more in detail since it might significantly affect any solution that might be offered. For example:

  • What is the nature of the data going over the network?
  • Does it have to be per minute? What if the network isn't done sending and the minute is up and you start reading?
  • What exactly does the ArrayList contain?
  • Can you describe the file output? (text file? serialized object? etc...)

Just an initial hunch on my part --some thoughts I would have when designing a solution for the problem you described would involve some kind of Producer-Consumer approach.

  • A Runnable/Thread object whose sole responsibility is to continuously read from the network, assemble the data and place it in a synchronized queue.
  • A Runnable/Thread object in a wait() state observing the synchronized queue. When signaled by the queue, it will start reading the contents of the queue for persistence to a file(s).
  • When there are items in the queue (or when a certain threshold is reached) it will notify() the waiting queue reader to start consuming the objects from the queue for persistence.

I maybe completely off base, but the fact that you're reading from the network implies some sort of unpredictability and unreliability. So instead of relying on timers, I would rely on the Producer of data (object reading from the network) signal the Consumer (the object that will use the data read from the network) to do something with the data.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top