summaryrefslogtreecommitdiff
path: root/src/main/Watcher.java
blob: 3f1db4729c151a9b49a0a38c4e19e2303e339b63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main;

import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * Prints some progress.
 *
 * @author Peter Wu
 */
public class Watcher implements Runnable {

    private final Progressable main;
    /**
     * Interval in seconds in which the status information is updated.
     */
    private final int interval;
    private final DateTimeFormatter df;
    private int elapsed_seconds = 0;
    private int previousCount = 0;

    public Watcher(Progressable main, int interval) {
        this.main = main;
        this.interval = interval;
        df = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
    }

    @Override
    public void run() {
        int newCount = main.getCount();
        if (newCount < 1) {
            // database connection is being established? Whatever is the case,
            // no status information should be printed.
            return;
        }
        int objects_per_min = (newCount - previousCount) * 60 / interval;
        int objects_per_sec = objects_per_min / 60;
        elapsed_seconds += interval;
        // objects per min based on total number of objects and elapsed time
        int total_objects_per_min = newCount * 60 / elapsed_seconds;
        String datetime = df.print(new LocalDateTime());
        // store new objects count for next sample
        previousCount = newCount;
        System.err.println(datetime + " Processed objects: " + newCount
                + " (total: " + total_objects_per_min + " objects/min)"
                + " (last interval: " + objects_per_sec + " objects/sec, "
                + objects_per_min + " objects/min)");
    }

    public interface Progressable {

        /**
         * @return The progress of the program or 0 if it was not started yet.
         * It must be a monotonically increasing value.
         */
        public int getCount();
    }
}