Search code examples
casynchronoustimerscheduled-tasksglib

Is there an algorithm to schedule overlapping turn-on/turn-off commands?


The problem I want to solve is as follow:

overlaping on/off scheduling

Each task (the green bar) represents a pair of turn-on (green-dashed-line) and turn-off (red-dashed-line) commands. Tasks may or may not overlap with one another. This a real-time application where we don't know when or if another task is coming. The goal is to turn the valve on if it's not already on and avoid turn off the valve prematurely.

What I mean by not turn off the valve prematurely is, for example, if we turn off the valve at time off-1, that's wrong because the valve should still stay on at that point in time, the correct action is to turn off the valve at time off-4.

Regarding the implementation details, each task is an async task (via. GLib async API). I simulate the waiting for task-duration with the sleep function, a timer is probably more appropriate. Right now, the tasks run independently and there is no coordination between them, thus the valve is being turn-off prematurely.

I searched around to find a similar problem but the closest I found is interval scheduling whose goal is different. Has anyone encountered a similar problem before and can give me some pointers on how to solve this problem?


Solution

  • It seems like this could be solved with a simple counter. You increment the counter for each opening command, and decrement it for each closing command - when the count reaches zero, you close the valve.