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

60
LINES

< > BotCompany Repo | #1013001 // TailFile

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (11180L/63K).

sclass TailFile implements AutoCloseable {
  File file;
  int interval;
  O onData;
  
  settable ISleeper sleeper = defaultSleeper();
  
  long l;
  gettable long currentFileSize;
  new Flag stopped;
  FlexibleRateTimer 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 = new FlexibleRateTimer(msIntervalToHertz(interval), -> {
      if (!stopped.isUp()) thread.trigger();
    });
    timer.sleeper(sleeper);
    timer.start();
  }
  
  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 #1009097

download  show line numbers  debug dex  old transpilations   

Travelled to 16 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ekrmjmnbrukm, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1013001
Snippet name: TailFile
Eternal ID of this version: #1013001/20
Text MD5: cfb8af254209ce8d76048bba7d62a9da
Transpilation MD5: 8159e53f96cfefff5b411ba5a6c44226
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:55:22
Source code size: 1420 bytes / 60 lines
Pitched / IR pitched: No / No
Views / Downloads: 516 / 1219
Version history: 19 change(s)
Referenced in: [show references]