Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make thread sleep for seconds in iOS?

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.

like image 222
Opart Code Avatar asked Mar 06 '15 09:03

Opart Code


People also ask

How do I make my thread sleep for 1 minute?

To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);

How do I make my current thread sleep?

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 .

What does sleep () do in Swift?

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.

How do you make a sleep in Swift?

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.


1 Answers

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

like image 100
Popeye Avatar answered Oct 20 '22 20:10

Popeye