aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java
blob: 0fdf4892f64a46f53dcf42c80167ebd42c607a8b (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
60
package me.xmrvizzy.skyblocker.utils;

import java.util.PriorityQueue;

public class Scheduler {
    private int currentTick;
    private final PriorityQueue<ScheduledTask> tasks;

    public Scheduler() {
        currentTick = 0;
        tasks = new PriorityQueue<>();
    }

    public void schedule(Runnable task, int delay) {
        assert delay > 0;
        ScheduledTask tmp = new ScheduledTask(currentTick + delay, task);
        tasks.add(tmp);
    }

    public void scheduleCyclic(Runnable task, int period) {
        new CyclicTask(task, period).run();
    }

    public void tick() {
        currentTick += 1;
        ScheduledTask task;
        while ((task = tasks.peek()) != null && task.schedule <= currentTick) {
            task.run();
            tasks.poll();
        }
    }

    private class CyclicTask implements Runnable {
        private final Runnable inner;
        private final int period;

        public CyclicTask(Runnable task, int period) {
            this.inner = task;
            this.period = period;
        }

        @Override
        public void run() {
            schedule(this, period);
            inner.run();
        }
    }

    private record ScheduledTask(int schedule, Runnable inner) implements Comparable<ScheduledTask>, Runnable {
        @Override
        public int compareTo(ScheduledTask o) {
            return schedule - o.schedule;
        }

        @Override
        public void run() {
            inner.run();
        }
    }
}