call function after defined seconds without using timer - iphone

I am calling a function after 180 seconds using timer. But the timer sometimes behaves in different manner and calls the function multiple times in 180 seconds.
please suggest me how to call a function after each 180 seconds untill I post stop message without using timer.
Code
if(!tmr_CallWebService)
{
tmr_CallWebService = [NSTimer scheduledTimerWithTimeInterval:180 target:ClassTracing selector:#selector(startLocationTracing) userInfo:nil repeats:YES];
}
Thanks in advance

I think there is a method to do this task, here use it like this
[self performSelector:#selector(yourMethodName) withObject:[NSArray arrayWithObjects:firstArgument,secondeArgument,nil] afterDelay:180];
use nil in place of array if you have no argument in that method.

You can use - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay from NSObject

Related

call method every 5 minutes in my UIView

I want to call a certain method in my UIView code say every 5 minutes - how do I accomplish that?
You can use an NSTimer:
Put the following in your viewDidLoad (where 300 is the number of seconds):
[NSTimer scheduledTimerWithTimeInterval:300.0f
target:self
selector:#selector(updateMethod:)
userInfo:nil
repeats:YES];
And then create your update method:
- (void)updateMethod:(NSTimer *)theTimer {
// Your code goes here
}
You can use NSTimer to do this.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html
Specifically, the
timerWithTimeInterval:target:selector:userInfo:repeats:
class method.
There is an easy way to do this, in you update method
-(void)update{
//Your update methods here
[self performSelector:#selector(update) withObject:nil afterDelay:300.0];
}

Write code instead of selector in like NSTimers?

Is there anyway to write code instead of setting a selector to method to call in NSTimer?
If i want to print hello world after 5 sec i can do it like this.
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(helloWorld:) userInfo:nil repeats:NO];
and have this function
-(void)helloWorld:(NSTimer*)aTimer {
NSLog(#"Hello World!");
}
But instead of writeing functions for every timer you have is it possible to add NSLog(#"Hello World!") in the same line as where i create the timer?
I use this code– an NSTimer category:
https://gist.github.com/250662/d4f99aa9bde841107622c5a239e0fc6fa37cb179
Some methods allow you to pass a code block as a parameter. Unfortunately this isn't supported for NSTimer.

How can I create an NSTimer that repeats twice and then stops

I'd like to create an NSTimer that repeats twice then stops and invalidates itself. I'd rather not use a loop if that's possible. Any thoughts on how I could do this?
Create a static int inside your timer delegate function that is initialized to 0.
Increment it each time the delegate is called.
When the counter reaches the value you wish invalidate the timer.
This is something your timer's target should handle, not something the timer itself should handle. You can either install a repeating timer and have the target invalidate it the second time it fires, or you can install a one-shot timer, reinstall it after the first time it fires, and then not set it up again the second time.
Basically, you need a state machine state variable that can be accessed both from the routine that initializes the timer, and from the timer's target.
Set the state variable to allow the first call to the timer task to restart the timer, but in that call also set that state variable so that subsequent calls do not restart.
Note that this kind of state variable can be used for any number of timer task repetitions, by simply decrementing it.
State machines are pretty much how all (synchronous) digital chips and logic works.
I very much disagree with the Jeremy that this is something that the target should handle. In fact I disagree so much that I have created my own Timer class, based on NSTimer, that you can configure in detail.
- (void) doSomething: (Timer*) timer
{
NSLog(#"This is iteration %d", timer.currentIteration);
}
- (void) startDoingSomething
{
Timer* timer = [Timer new];
timer.interval = 5.0; // Fire every 5 seconds
timer.delay = 2.5; // Start firing after 2.5 seconds
timer.iterations = 3; // Only fire three times
timer.target = self;
timer.selector = #selector(doSomething:);
[timer schedule];
// Don't forget to release timer somewhere - the above is just an example
}
See http://github.com/st3fan/ios-utils
One solution might look similar to this.
Launching the timer
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(timerMethod:) userInfo:nil repeats:YES];
Handling the timer and repetitions
int repetitions = 2; //EDIT: remove static declaration (see below)
- (void)timerMethod:(NSTimer*)theTimer{
NSLog(#"Timer fired");
repetitions--;
if(repetitions == 0){
[theTimer invalidate];
NSLog(#"Timer stopped");
}
}
EDIT:
I removed the static modifier above to make a more generic example. The original intent of the static was to persist the timer across objects of similar type, a request that the OP did not make.

I should able to delay 2 seconds using NSTimer. How to do it?

I want to produce a delay of 2 seconds using NSTimer how to initialize timer in program?
Multiple options here.
If you just want a delay of 2 seconds you could use the sleep() function
#include<unistd.h>
...
sleep(2);
Or you may be able to use NSTimer like so
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(fireMethod) userInfo:nil repeats:NO];
And in your class you would have a method defined as
-(void)fireMethod
{
//Do stuff
}
Here you go...
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:#selector(action)
userInfo:nil
repeats:NO];
Simple answer: [NSThread sleepForTimeInterval:10.0];
Note that you should not really be thinking about delays in an event driven UI/OS. You should thinking about tasks you want to do now, and tasks you want to do later, and code these subtasks and schedule them appropriately. e.g. instead of:
// code that will block the UI when done in the main thread
- (void) methodC {
doA();
delay(2);
doB();
}
you might want to have code that looks more like:
- (void) methodA {
doA();
return; // back to the run loop where other useful stuff might happen
}
- (void) methodB {
doB();
}
and you can then schedule methodB with an NSTimer at the end of methodA, an NSTimer started by whatever called methodA, or, the best option, by the asynchronous completion routine of something started by methodA.

Objective C equivalent to javascripts setTimeout?

I was wondering whether there is a solution to raise an event once after 30 seconds or every 30 seconds in CocoaTouch ObjectiveC.
The performSelector: family has its limitations. Here is the closest setTimeout equivalent:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
// do work in the UI thread here
});
EDIT:
A couple of projects that provide syntactic sugar and the ability to cancel execution (clearTimeout):
https://github.com/Spaceman-Labs/Dispatch-Cancel
https://gist.github.com/zwaldowski/955123
There are a number of options.
The quickest to use is in NSObject:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
(There are a few others with slight variations.)
If you want more control or to be able to say send this message every thirty seconds you probably need NSTimer.
Take a look at the NSTimer class:
NSTimer *timer;
...
timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:#selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
[timer fire];
Somewhere else you have the actual method that handles the event:
- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
NSLog(#"fired!");
}
+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
Documentation
You may also want to look at the other NSTimer methods