In iOS env, is it possible to make current thread sleep for seconds, then execute my code? NSTimer, GDC or any technique is okay for me.
To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
sleep() is the new async API that does “sleep”. It suspends the current Task instead of blocking the thread — that means the CPU core is free to do something else for the duration of the sleep.
You need to call Task. sleep() using await as it will cause the task to be suspended, and you also need to use try because sleep() will throw an error if the task is cancelled. Important: Calling Task. sleep() will make the current task sleep for at least the amount of time you ask, not exactly the time you ask.
It would be better if you shared what you have done but it here you go.
There are a few options you can go with:
Option 1
// Standard Unix calls
sleep();
usleep();
Some documentation regarding the sleep
function can be found here. You'll find that they are actually C
functions but since Objective-C
is a strict superset of C we can still use the sleep
and usleep
functions.
Option 2
[NSThread sleepForTimeInterval:2.000];//2 seconds
The Apple documentation for this method states:
Sleeps the thread for a given time interval.
Discussion
No run loop processing occurs while the thread is blocked.
Option 3
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
1 * NSEC_PER_SEC),
dispatch_get_main_queue(),
^{
// Do whatever you want here.
});
The Grand Central Dispatch
route is a pretty good way of doing things as well. Here is the Apple Documentation for Grand Central Dispatch which is quite a good read.
There is also this question that might be pretty useful How to Wait in Objective-C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With