1

I'd like to execute a piece of code every 500ms for a total of 10 seconds. I have the code working executing every half a second with this code

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];

but I cannot seem to figure out how to stop it executing after 10 seconds. The "repeats" argument doesnt seem to allow for a specified time. Could someone point me in the direction of where I should go with this?

Thanks Brian

Brian Boyle
  • 2,849
  • 5
  • 27
  • 35

4 Answers4

5

You need to message invalidate on the NSTimer that scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: gives you. For example assign the NSTimer that method returns to you in a property or iVar of your class and after 10 seconds call invalidate on it.

Example:

.h:

@interface myClass{
NSTimer *myT;
}
[...]

.m:

[...]
{
    myT = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];

    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(stop) userInfo:nil repeats:NO];
}

-(void)stop{
    [myT invalidate];
}
[...]

You could avoid another NSTimer if you want by implementing some kind of finish flag and track how many times you messaged the getLevel method, since it's every .5 seconds, that'll be 20 times.

But I would rather 2 NSTimer objects because you know it's 10 seconds regardless of the other timer, which you might decide to change, up or down it's frequency...

Daniel
  • 23,129
  • 12
  • 109
  • 154
1

The best thing to do is make a property on your class.

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) int ticks;

then in your getLevel selector call this:

if (ticks >= 20) [self.timer invalidate];
// 20 is 10 seconds * 500 milliseconds
ticks++;
Matt Hudson
  • 7,329
  • 5
  • 49
  • 66
1

Another way you could go would be to define a selector, say -(void)stopTimer{} in which you invalidate the timer. Then when you create the Timer in the first place do one of these:

[self performSelector:@selector(stopTimer) withObject:nil afterDelay:10.0];

jacerate
  • 456
  • 3
  • 8
0

You can set another timer to stop it using invalidate. Just keep a reference for this timer in an ivar or property.

Check this answer for more information.

Community
  • 1
  • 1
Selkie
  • 1,773
  • 1
  • 14
  • 21