summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/autobackup/AutoBackupDispatcher.java
blob: 32d626eb2f1e2e76e813abcf7d79a0935f56437b (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
package com.keuin.kbackupfabric.autobackup;

import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

public class AutoBackupDispatcher {

    private Timer timer = null;
    private final Logger logger = Logger.getLogger(AutoBackupDispatcher.class.getName());
    private boolean skipIfNoPlayerLoggedIn;
    private final PlayerActivityTracker playerActivityTracker;

    public AutoBackupDispatcher(int intervalSeconds, boolean skipIfNoPlayerLoggedIn, PlayerActivityTracker playerActivityTracker) {
        this.skipIfNoPlayerLoggedIn = skipIfNoPlayerLoggedIn;
        this.playerActivityTracker = playerActivityTracker;
        if (intervalSeconds > 0)
            setInterval(intervalSeconds);
    }

    public synchronized void setInterval(int intervalSeconds) {
        Optional.ofNullable(timer).ifPresent(Timer::cancel);
        Timer newTimer = new Timer("AutoBackupTimer");
        newTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                toggleBackup();
            }
        }, 0L, intervalSeconds * 1000L);
        timer = newTimer;
    }

    public void setSkipIfNoPlayerLoggedIn(boolean skipIfNoPlayerLoggedIn) {
        this.skipIfNoPlayerLoggedIn = skipIfNoPlayerLoggedIn;
    }

    public synchronized void stop() {
        timer.cancel();
        timer = null;
    }

    private void toggleBackup() {
        if (playerActivityTracker.getCheckpoint() || !skipIfNoPlayerLoggedIn) {
            logger.info("Interval backup event is triggered.");
            // TODO: perform a backup
        }
    }

}