Reputation: 526
The situation is following:
Food
) in database (in my case it's MySQL).State
which is enumerable taking one of "FRESH", "STALE" or "SPOILED".Bottle of milk
is created with FRESH
state, but after 2 days it becomes STALE
, then after next 3 days it becomes SPOILED
.The question is: is there any pattern that allows me to control states of objects and change them accordingly? For instance, I can run some script every 30 minutes, select all the objects, inspect their states and change them. But this approach looks suboptimal, I'm trying to find out something better.
Edit Running a routine each 30 minutes adds load to database (because each time I ned to select records for analysis). I'm trying to find a solution that:
I could use some smart scheduler that keeps an ordered map like timestamp -> [(object_id, next_state)]
in memory (up to 128G is available for this task).
Upvotes: 0
Views: 72
Reputation: 35901
As noted by JB Nizet, the state property does not need to be stored in the database.
In general, the design pattern for an entity that periodically does some clean-up, maintenance, etc. is called the Agent design pattern.
In your case:
class FoodStateAgent
{
void Run() // called periodically from a Scheduler
{
// ...
}
};
Agents usually work together with Schedulers - classes responsible for running specific actions on their defined deadline's.
Upvotes: 0
Reputation: 691943
You shouldn't store the state in the database. You should store the moment it becomes stale, and the moment it becomes spoiled.
That way, you don't need to ever change anything in the database.
To get items that are spoiled, you just need a query like
select * from item where now() >= spoileddate
To get items that are stale, you just need a query like
select * from item where now() >= staledate and now() < spoileddate
To get items that are fresh, you just need a query like
select * from item where now() < staledate
That, BTW, has another advantage: you can know the state of an item at any given time, and not just its current state. So if you get a phone call asking "I ate product xyz three days ago, am I safe?", you can answer.
Upvotes: 2