Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

55
LINES

< > BotCompany Repo | #1036375 // TailFile backup using java.util.Timer

JavaX fragment (include)

sclass TailFile implements AutoCloseable {
  File file;
  int interval;
  O onData;
  long l;
  gettable long currentFileSize;
  new Flag stopped;
  java.util.Timer timer;
  ReliableSingleThread thread;
  volatile bool hasIdled, debug;
  
  *() {}
  *(final File *file, int *interval, O *onData) {
    thread = new ReliableSingleThread(r { update() });
  }
  
  void update {
    long l2 = currentFileSize = l(file);
    if (l2 < l) l = 0; // file shrunk (log rotated!) - start over from beginning of file
    if (l2 == l) hasIdled = true;
    else pcall {
      if (debug) print("New data in " + f2s(file) + ": " + n2(l2-l, "byte"));
      for (S s : loadTextFilePart_iterator(file, l, l2))
        pcallF(onData, s);
      l = l2;
    }
  }
  
  void start {
    timer = doEvery(interval, r {
      if (!stopped.isUp()) thread.trigger()
    });
  }
  
  void stop {
    timer.cancel();
    timer = null;
    if (stopped.raise())
      thread.triggerAndWait(); // One last time baby
  }
  
  public void close { stop(); }
  
  bool started() {
    ret timer != null;
  }
  
  void debugOn {
    if (debug) ret;
    debug = true;
    print("Watching file: " + f2s(file));
  }
  
  toString { ret "Tailing file " + file; }
}

Author comment

Began life as a copy of #1013001

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1036375
Snippet name: TailFile backup using java.util.Timer
Eternal ID of this version: #1036375/1
Text MD5: 24961a79b69ae9985ac87d1569ad5a4f
Author: stefan
Category: javax / i.o.
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-11-28 20:43:40
Source code size: 1277 bytes / 55 lines
Pitched / IR pitched: No / No
Views / Downloads: 109 / 121
Referenced in: [show references]