I have an application where a person is allowed to set alarm for particular events for particular time and days. For eg:-
there are two events- A & B and these events occur repeatedly on certain days of the week schedule of these events go like:
EVENT A – occurs every SUNDAY,MONDAY and WEDNESDAY at 7am and 9pm.
EVENT B – occurs every SUNDAY and TUESDAY at 6am and 8pm.
EVENT C – occurs every MONDAY,WEDNESDAY and THURSDAY at 8am,9pm.
The user is shown a form where he can select the days and enter the timings which are same for all the days selected.He can create as many events as he wants.
In the DB as of now I have created 7 columns for each of the days and one column for the timings. I know I might be making it unnecesarily complicated. The above data is represented as
EventNAME SUN MON TUE WED THU FRI SAT Timings
A 1 1 0 1 0 0 0 7,21
B 1 0 1 0 0 0 0 6,20
C 0 1 0 1 1 0 0 8,21
Now for some reason I have to find the next nearest day and time when an event occurs For eg: if today is wednesday morning 6am , I have to get the next nearest event as event a -morning 7 am. and at wednesday morning 8 am, I have to get the next nearest event as event C at morning 8 am.
How do I get the next nearest day and time from such a schema? Is there a better way of designing the table?
I’d use a second table with two colums:
(event_id, next_run_time)Whenever you add an event to the schedule table, calculate the next time it should fire. Build a function for that. The logic would be:
1, and one of the timings is in the future)Then figuring out what needs to be run is a simple matter of (pseudo-sql):
And whenever you trigger the task, update its next run time using the same function you built earlier.
Careful: you’ll need some form of locking to prevent a task from being run twice if to “scheduler”s run at the same time.
I’m not sure whether having a column for each day of the week is useful, unless you want to query specifically for “jobs scheduled on Wednesdays” for instance. A more compact format (like a plain string with
0101100for your last task for instance) could be more practical depending on your programming language and exact query needs. (Or possibly redesign that table with(event_id, day_number, timing)(singular “timing”), selection of the “next runtime” would be easier.)