m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/modules/TimerScheduler.java
blob: 9390940124063c75eb69460ead25f1c84d848d90 (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
package pl.edu.mimuw.cloudatlas.agent.modules;

import pl.edu.mimuw.cloudatlas.agent.messages.AgentMessage;
import pl.edu.mimuw.cloudatlas.agent.messages.TimerSchedulerMessage;

import java.util.Timer;

/**
 * Initializes a timer within a constructor during its attachment to the executor
 * Runs in a thread separate from executor - maybe refactor so that it's attached to executor's thread
 *
 * Handle used to attach tasks to schedule
 * Tasks declared as inherited from TimerTask
 *
 * TODO: add request id and custom time
 */
public class TimerScheduler extends Module {
    private Timer timer;

    public TimerScheduler(AgentMessage.AgentModule moduleType) {
        super(moduleType);
        assert moduleType == AgentMessage.AgentModule.TIMER_SCHEDULER;
        this.timer = new Timer();
        System.out.println("TimerScheduler instance initialized");
    }

    @Override
    public void handle(AgentMessage event) throws InterruptedException {
        assert event.getDestinationModule() == event.getCorrectMessageType();
        TimerSchedulerMessage timerEvent = (TimerSchedulerMessage) event;
        addTask(timerEvent);
    }

    public void addTask(TimerSchedulerMessage msg) {
        TimerScheduledTask task = msg.getTask();
        task.setScheduler(this);
        this.timer.schedule(task, msg.getDelay());
        System.out.println("Task with delay " + msg.getDelay() + " scheduled");
    }

    // TODO
    public void removeTask(String requestId) {}

    public void passMessageFromTask(AgentMessage msg) throws InterruptedException {
        this.executor.passMessage(msg);
    }
}