Re: Best pattern to follow for scheduling an event
Re: Best pattern to follow for scheduling an event
- Subject: Re: Best pattern to follow for scheduling an event
- From: Army Research Lab <email@hidden>
- Date: Thu, 08 Nov 2007 14:59:48 -0500
- Thread-topic: Best pattern to follow for scheduling an event
> I have a method that needs to schedule a "cleanup pass" to occur in
> the near future. The method might be called once, ten times, or a
> hundred times in a row, but I only need to clean up one time. To
> implement this, I used the following pattern, and I'm wondering if it
> was the best way to go.
>
> First, when the object is first created, I create a timer. I
> scheduled its fire date to be in the distant, distant future:
>
> m_deferredFixupTimer = [[NSTimer
> scheduledTimerWithTimeInterval:DBL_MAX
> target:myObject
> selector:@selector(doFixUp:)
> userInfo:NULL
> repeats:YES] retain];
>
> (I considered using INFINITY instead of DBL_MAX, but sometimes
> library code isn't prepared to deal with infinite values, so I
> figured DBL_MAX is safer and already more than large enough.)
> Then, when my method is called, I schedule the timer to fire
> immediately:
>
> [m_deferredFixupTimer setFireDate:[NSDate date]];
>
> This defers the fire to the next run-through of the event loop, which
> for my purposes is sufficient. It only fires one time.
>
> So is this the right way to do it? It seems to work in practice, it
> just seemed a little quirky to me for some reason. I guess it would
> make more sense if I could make a timer that's scheduled to never
> fire, instead of a timer that's scheduled to repeat and fire once
> every trillion years. But in practice it seems to be equivalent.
OK, how about something like this?
@interface myObject : NSObject
{
NSTimer * m_deferredFixupTimer;
}
- (void) fixupLater(void);
@end
@implementation
- (id)init
{
if (self = [super init])
{
m_deferredFixupTimer = [[NSTimer
scheduledTimerWithTimeInterval:DBL_MAX
target:myObject
selector:@selector(doFixUp:)
userInfo:NULL
repeats:YES] retain];
}
return self;
}
- (void) fixupLater(void)
{
[m_deferredFixupTimer setFireDate:
[NSDate dateWithTimeIntervalSinceNow:1]];
}
@end
(banged out rapidly, no testing, YMMV)
Every time your call to fixupLater() is made, the timer is deferred for a
short while. A flurry of calls just pushes back when the fix up occurs, and
it doesn't matter how many calls were made before the fix up happened.
Good luck,
Cem Karan
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden