С delay function windows

Sleep function (synchapi.h)

Suspends the execution of the current thread until the time-out interval elapses.

To enter an alertable wait state, use the SleepEx function.

Syntax

Parameters

The time interval for which execution is to be suspended, in milliseconds.

A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.WindowsВ XP:В В A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. This behavior changed starting with Windows ServerВ 2003.

A value of INFINITE indicates that the suspension should not time out.

Return value

Remarks

This function causes a thread to relinquish the remainder of its time slice and become unrunnable for an interval based on the value of dwMilliseconds. The system clock «ticks» at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on. To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum. Use caution when calling timeBeginPeriod, as frequent calls can significantly affect the system clock, system power usage, and the scheduler. If you call timeBeginPeriod, call it one time early in the application and be sure to call the timeEndPeriod function at the very end of the application.

After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. For more information, see Scheduling Priorities.

Be careful when using Sleep in the following scenarios:

  • Code that directly or indirectly creates windows (for example, DDE and COM CoInitialize). If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. If you have a thread that uses Sleep with infinite delay, the system will deadlock.
  • Threads that are under concurrency control. For example, an I/O completion port or thread pool limits the number of associated threads that can run. If the maximum number of threads is already running, no additional associated thread can run until a running thread finishes. If a thread uses Sleep with an interval of zero to wait for one of the additional associated threads to accomplish some work, the process might deadlock.

For these scenarios, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than Sleep.

Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.

WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.

Читайте также:  Asus wireless console для windows

Task. Delay Метод

Определение

Создает задачу, которая будет выполнена после некоторой временной задержки. Creates a task that will complete after a time delay.

Перегрузки

Создает отменяемую задачу, которая завершается через заданное количество миллисекунд. Creates a cancellable task that completes after a specified number of milliseconds.

Создает отменяемую задачу, которая завершается через заданное время. Creates a cancellable task that completes after a specified time interval.

Создает задачу, которая завершается через заданное количество миллисекунд. Creates a task that completes after a specified number of milliseconds.

Создает задачу, которая завершается через заданное время. Creates a task that completes after a specified time interval.

Delay(Int32, CancellationToken)

Создает отменяемую задачу, которая завершается через заданное количество миллисекунд. Creates a cancellable task that completes after a specified number of milliseconds.

Параметры

Число миллисекунд, в течение которого ожидается завершение возвращаемой задачи, или -1 для неограниченного времени ожидания. The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.

Токен отмены, который нужно контролировать во время ожидания выполнения задачи. A cancellation token to observe while waiting for the task to complete.

Возвращаемое значение

Задача, представляющая временную задержку. A task that represents the time delay.

Исключения

Аргумент millisecondsDelay меньше –1. The millisecondsDelay argument is less than -1.

Задача была отменена. The task has been canceled.

Предоставленный объект cancellationToken уже удален. The provided cancellationToken has already been disposed.

Примеры

В следующем примере запускается задача, которая включает вызов Delay(Int32, CancellationToken) метода с задержкой в одну секунду. The following example launches a task that includes a call to the Delay(Int32, CancellationToken) method with a one second delay. До истечения интервала задержки маркер отменяется. Before the delay interval elapses, the token is cancelled. Выходные данные в примере показывают, что в результате TaskCanceledException создается исключение, а Status свойству Tasks — значение Canceled . The output from the example shows that, as a result, a TaskCanceledException is thrown, and the tasks’ Status property is set to Canceled.

Комментарии

Значение, если маркер отмены сообщается до заданной задержки, TaskCanceledException результата исключения и задача завершается в Canceled состоянии. If the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. В противном случае задача будет завершена в RanToCompletion состоянии после истечения заданной задержки. Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

Сценарии использования и дополнительные примеры см. в документации по Delay(Int32) перегрузке. For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

Этот метод зависит от системных часов. This method depends on the system clock. Это означает, что задержка времени будет приблизительно равна разрешению системных часов millisecondsDelay , если аргумент меньше, чем разрешение системных часов, что составляет примерно 15 миллисекунд на системах Windows. This means that the time delay will approximately equal the resolution of the system clock if the millisecondsDelay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

Применяется к

Delay(TimeSpan, CancellationToken)

Создает отменяемую задачу, которая завершается через заданное время. Creates a cancellable task that completes after a specified time interval.

Параметры

Время, в течение которого ожидается завершение возвращаемой задачи, или TimeSpan.FromMilliseconds(-1) для неограниченного времени ожидания. The time span to wait before completing the returned task, or TimeSpan.FromMilliseconds(-1) to wait indefinitely.

Токен отмены, который нужно контролировать во время ожидания выполнения задачи. A cancellation token to observe while waiting for the task to complete.

Возвращаемое значение

Задача, представляющая временную задержку. A task that represents the time delay.

Исключения

delay представляет отрицательный интервал времени, отличный от TimeSpan.FromMilliseconds(-1) . delay represents a negative time interval other than TimeSpan.FromMilliseconds(-1) .

— или — -or- Свойство TotalMilliseconds аргумента delay больше, чем MaxValue. The delay argument’s TotalMilliseconds property is greater than MaxValue.

Читайте также:  Файловый менеджер для windows server

Задача была отменена. The task has been canceled.

Предоставленный объект cancellationToken уже удален. The provided cancellationToken has already been disposed.

Примеры

В следующем примере запускается задача, которая включает вызов Delay(TimeSpan, CancellationToken) метода с задержкой 1,5 секунд. The following example launches a task that includes a call to the Delay(TimeSpan, CancellationToken) method with a 1.5 second delay. До истечения интервала задержки маркер отменяется. Before the delay interval elapses, the token is cancelled. Выходные данные в примере показывают, что в результате TaskCanceledException создается исключение, а Status свойству Tasks — значение Canceled . The output from the example shows that, as a result, a TaskCanceledException is thrown, and the tasks’ Status property is set to Canceled.

Обратите внимание, что этот пример включает потенциальное условие состязания: это зависит от задачи, которая асинхронно выполняет задержку при отмене маркера. Note that this example includes a potential race condition: it depends on the task asynchronously executing the delay when the token is cancelled. Хотя задержка 1,5 секунд из вызова Delay(TimeSpan, CancellationToken) метода делает это допущением, тем не менее возможно, что вызов Delay(TimeSpan, CancellationToken) метода может быть возвращен до отмены маркера. Although the 1.5 second delay from the call to the Delay(TimeSpan, CancellationToken) method makes that assumption likely, it is nevertheless possible that the call to the Delay(TimeSpan, CancellationToken) method could return before the token is cancelled. В этом случае в примере выводится следующий результат: In that case, the example produces the following output:

Комментарии

Значение, если маркер отмены сообщается до заданной задержки, TaskCanceledException результата исключения и задача завершается в Canceled состоянии. If the cancellation token is signaled before the specified time delay, a TaskCanceledException exception results, and the task is completed in the Canceled state. В противном случае задача будет завершена в RanToCompletion состоянии после истечения заданной задержки. Otherwise, the task is completed in the RanToCompletion state once the specified time delay has elapsed.

Сценарии использования и дополнительные примеры см. в документации по Delay(Int32) перегрузке. For usage scenarios and additional examples, see the documentation for the Delay(Int32) overload.

Этот метод зависит от системных часов. This method depends on the system clock. Это означает, что задержка времени будет приблизительно равна разрешению системных часов delay , если аргумент меньше, чем разрешение системных часов, что составляет примерно 15 миллисекунд на системах Windows. This means that the time delay will approximately equal the resolution of the system clock if the delay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

How do you add a timed delay to a C++ program?

I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?

I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.

14 Answers 14

sleep() only takes a number of seconds which is often too long.

An updated answer for C++11:

Use the sleep_for and sleep_until functions:

With these functions there’s no longer a need to continually add new functions for better resolution: sleep , usleep , nanosleep , etc. sleep_for and sleep_until are template functions that can accept values of any resolution via chrono types; hours, seconds, femtoseconds, etc.

In C++14 you can further simplify the code with the literal suffixes for nanoseconds and seconds :

Note that the actual duration of a sleep depends on the implementation: You can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that’s the shortest it can do.

Читайте также:  Linux сделать все файлы исполняемыми

This will also sleep for three seconds. You can refine the numbers a little more though.

Do you want something as simple like:

Note that this does not guarantee that the amount of time the thread sleeps will be anywhere close to the sleep period, it only guarantees that the amount of time before the thread continues execution will be at least the desired amount. The actual delay will vary depending on circumstances (especially load on the machine in question) and may be orders of magnitude higher than the desired sleep time.

Also, you don’t list why you need to sleep but you should generally avoid using delays as a method of synchronization.

You can try this code snippet:

You can also use select(2) if you want microsecond precision (this works on platform that don’t have usleep(3))

The following code will wait for 1.5 second:

Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you’re guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.)
Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.

I found that «_sleep(milliseconds);» (without the quotes) works well for Win32 if you include the chrono library

Make sure you include the underscore before sleep.

to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file syntax for Sleep() function is Sleep(time_in_ms) as

OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.

The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).

void sleep(unsigned seconds);

sleep() suspends execution for an interval (seconds). With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.

Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.

If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this.

I don’t know what OS you are trying to do this on, but for threading and synchronisation you could look to the Boost Threading libraries (Boost Condition Varriable).

Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a ‘sleep’ is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case. For really short ‘waits’ you can try an assembly «nop». I highly doubt these are what you are after but without knowing why you need to wait it’s hard to be more specific.

Оцените статью