Logical ways to calculate being within two timesby stevieb (Canon)
|on Nov 22, 2016 at 21:44 UTC||Need Help??|
stevieb has asked for the wisdom of the Perl Monks concerning the following question:
This is more a theoretical question than one of problematic code, but I've been fighting with this off and on for a few days now so I seek advice.
I have an event loop running in a separate process every three seconds. This event decides to turn a light on at a specific time of day, and then turns it off X hours later.
What I need to do is the following. Let's use 2000 (8pm) for lights on, and 12 for the number of hours the lamp should remain on:
Because on/off can cross the midnight boundary, calculating by hour/minute alone doesn't work correctly, reliably.
I have a DB backend that I can store epoch in for when lights-on is to happen, as well as for lights-off. I can also create two class variables to store those DateTime objects so I'm not recreating them every three seconds.
I've tried all manner of things, but either accuracy or performance suffers, and I just can't get it right.
I'm thinking something along the lines of the following pseudo code, but am wondering if someone can suggest alternate/better ideas.
What I'm for some reason struggling with, is re-setting the lights-on DB entry/datetime when midnight hits (so that it reflects the current day). If I do it in a separate event, that can and will throw off the next check on the 3 second event. I can't do it in lights-off routine, because if lights run from say 0600-1800, the clock will be set back to 0600 for current day, and won't go on tomorrow. I can't set it in the lights-on routine, for similar reasons. I know I could add a day depending on the time of day, but that's too much work and prone for error if the lights-on time changes.
Perhaps one way would be to check the current time in the lights-off routine as it's about to turn the light off, and if its before midnight, add a day to the next lights-on dt, but I'm afraid I'm way overthinking things here.
Note: the light will always only have one on period within each 24 hour period (regardless of when it is within that window).