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.

This is my first thought of how to implement this:
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.