elgris
elgris

Reputation: 526

Is there any pattern for changing the state of the object on schedule?

The situation is following:

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:

  1. makes minimum requests to RDBMS (MySQL in my case)
  2. produces minimal lag between actual status change and a time a routine starts (running a routine each 30 minutes means some records will change their state with 30 minutes delay at most)
  3. extendable, because there may be more states to be supported (that's why JB Nizet's answer won't work for me)

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

Answers (2)

BartoszKP
BartoszKP

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

JB Nizet
JB Nizet

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

Related Questions