I have a list of items from which I want to continously return a random item, but I need to embargo any returned item until the next top of the hour. This requirement is because I'm dealing with a webservice that resets it's rate limit at the top of the hour. And to deal with different server times, I also need to embargo any item returned before 5 minutes of the top of the hour until the top of the 2nd hour (ex. if the item was used at 14:55:01, it should be embargoed until 16:00).
Is there any existing datastructure or module that would make this easy to implement? I want to make this efficient as well, so I don't want to have to loop through all the items to find the next available one.
package List::ResetOnTheHour; sub new { my $class = shift; my $self = { list => [@_], embargo_1_hour => [], embargo_2_hour => [], last_check => 0, }; return bless $self, $class; } sub next { my $self = shift; my $list = $self->{list}; # compare last_check against time and push embargo_1_hour back # onto list if the top of the hour has passed. push embargo_2_hour # onto embargo_1_hour or list depending upon how much time has # passed. my $next = splice @$list, -1 + int rand @$list, 1; # if within 5 minutes of next top of hour, push onto # embargo_2_hour, # else push onto embargo_1_hour return $next; } # This would be used instead of the constructor to add items when a # last used time is already known, like when reading from a # serialized state file on startup. sub add { my ($self, $elem, $time) = @_; # add to list or embargo_X_hour depending on value of time. }
In reply to Embargo algorithm by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |