nonamelive
nonamelive

Reputation: 6510

How to ensure sending less than 5 requests in a minute.

I'm using ASIHTTPRequest to send 100+ pending requests in a queue, but the server has a limit that a single IP cannot send more than 5 requests in a minute. How could I ensure this by using ASIHTTPRequest and ASINetworkQueue? Thoughts?

Thank you in advance.

Kai.

Upvotes: 1

Views: 258

Answers (2)

Mihai Fratu
Mihai Fratu

Reputation: 7663

What you can do is build your requests and store them in an AVMutableArray and than have a timer that checks for every 15 seconds (15 * 5 = 60) if there are any requests in your. For example in your h file you can have something like

@property (nonatomic, retain) NSTimer *queueTimer;
@property (nonatomic, retain) NSMutableArray *requestsQueue;

- (void)sendRequest;

In your m file you should than write this:

@@synthesize queueTimer = _queueTimer;
@@synthesize requestsQueue = _requestsQueue;

- (void)viewDidLoad:
{
    self.requestsQueue = [NSMutableArray array];
    self.queueTimer = [NSTimer timerWithTimeInterval:15 target:self selector:@selector(sendRequest) userInfo:nil repeats:YES];
}

Than whenever you create your requests instead of sending them to the server you put them in this array

[self.requestsQueue addObject:request];

And here is the sendRequest method:

- (void)sendRequest
{
    if ([self.requestsQueue count]) {
        id request = [self.requestsQueue objectAtIndex:0];
        // dispatch your request
        [self.requestsQueue removeObject:request];
    }
}

Also don't forget in your dealloc method to invalidate the timer as such

[queueTimer invalidate];

Hope this helps. Let me know if something went wrong.

Upvotes: 1

brain
brain

Reputation: 5546

I don't think either NSOperationQueue of ASINetowrkQueue let you do this directly so you have two options:

  1. Subclass NSOperationQueue/ASINetworkQueue and add support for limiting requests per minute, have a look at the bandwidth throttling they already do.
  2. Only add 5 operations per minute to the queue - create a list of 100+ ASIHTTPRequests, add 5 of them to the ASINetworkQueue and track when they finish using the delegate.

Of the solutions 2) might be easier to do because you don't have to dig into the ASI code but 1) is definitely cleaner and you could share the code with other people who I'm sure would find it useful.

Upvotes: 0

Related Questions