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

1  
sclass TailFile implements AutoCloseable {
2  
  File file;
3  
  int interval;
4  
  O onData;
5  
  
6  
  settable ISleeper sleeper = defaultSleeper();
7  
  
8  
  long l;
9  
  gettable long currentFileSize;
10  
  new Flag stopped;
11  
  FlexibleRateTimer timer;
12  
  ReliableSingleThread thread;
13  
  volatile bool hasIdled, debug;
14  
  
15  
  *() {}
16  
  *(final File *file, int *interval, O *onData) {
17  
    thread = new ReliableSingleThread(r { update() });
18  
  }
19  
  
20  
  void update {
21  
    long l2 = currentFileSize = l(file);
22  
    if (l2 < l) l = 0; // file shrunk (log rotated!) - start over from beginning of file
23  
    if (l2 == l) hasIdled = true;
24  
    else pcall {
25  
      if (debug) print("New data in " + f2s(file) + ": " + n2(l2-l, "byte"));
26  
      for (S s : loadTextFilePart_iterator(file, l, l2))
27  
        pcallF(onData, s);
28  
      l = l2;
29  
    }
30  
  }
31  
  
32  
  void start {
33  
    timer = new FlexibleRateTimer(msIntervalToHertz(interval), -> {
34  
      if (!stopped.isUp()) thread.trigger();
35  
    });
36  
    timer.sleeper(sleeper);
37  
    timer.start();
38  
  }
39  
  
40  
  void stop {
41  
    timer.cancel();
42  
    timer = null;
43  
    if (stopped.raise())
44  
      thread.triggerAndWait(); // One last time baby
45  
  }
46  
  
47  
  public void close { stop(); }
48  
  
49  
  bool started() {
50  
    ret timer != null;
51  
  }
52  
  
53  
  void debugOn {
54  
    if (debug) ret;
55  
    debug = true;
56  
    print("Watching file: " + f2s(file));
57  
  }
58  
  
59  
  toString { ret "Tailing file " + file; }
60  
}

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: 612 / 1333
Version history: 19 change(s)
Referenced in: [show references]