0

Dear community. I try to setup NSTimer:

@interface GetExternalInfo : NSOperation {

NSTimer *keepAliveTimerMain;

@property (nonatomic,retain) NSTimer *keepAliveTimerMain;

.m:

@synthesize keepAliveTimerMain

-(void) main;
{
self.keepAliveTimerMain = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(keepAlive:) userInfo:nil repeats:YES];
[keepAliveTimerMain fire];
[[NSRunLoop currentRunLoop] addTimer:self.keepAliveTimerMain forMode: NSDefaultRunLoopMode];

BOOL timerState = [keepAliveTimerMain isValid];
NSLog(@"STAT:Timer Validity is: %@", timerState?@"YES":@"NO");


- (void)keepAlive:(NSTimer *)theTimer
{
    BOOL currentState = [self isCancelled];
    NSLog(@"STAT:cancelled state is %@.\n",currentState?@"YES":@"NO");
}

In Logs

2011-02-02 18:58:31.041 snow[54705:5d07] STAT:cancelled state is NO. 2011-02-02 18:58:31.042 snow[54705:5d07] STAT:Timer Validity is: YES

i see this only once. No next repeat attempts every 5 seconds any opinions in this case? GC is enabled.

Alex
  • 393
  • 6
  • 21

2 Answers2

2

Do you have a runloop in the current thread? The timer needs a runloop to be able to fire. I notice you call -fire manually which explains why -keepAlive is called, but this doesn't actually start the timer.

Frederik Slijkerman
  • 6,471
  • 28
  • 39
  • i was try to do this, but i guess in incorrect place. i was try to do it from init method. As i understand now, init method working in other thread, where my timer can't fire. i will try and let u know result – Alex Feb 02 '11 at 19:07
1

You need to add your timer to a run loop, something like [[NSRunLoop currentRunLoop] addTimer:keepAliveTimerMain forMode: NSDefaultRunLoopMode];.

EDIT: The code you posted shows that you manually fire the timer before adding it to the runloop. This will fire and invalidate the timer, so you are actually trying to schedule an invalid timer on the runloop. That is why you only see the NSLog message once.

Richard
  • 3,316
  • 30
  • 41