Question

How can I make my VB program sleep for 5 seconds?

Asked by: shivermetimbers

Im sure there is probably a really simple solution to this question but I just can't solve it.

How can I make my VB program sleep or pause for say 5 seconds?

Any help would be much appreciated.

Sean.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-07 at 02:27:55ID20843293
Tags

sleep

,

vb

Topic

Visual Basic Programming

Participating Experts
13
Points
50
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Sleep API
    I am trying to use the Sleep API function to put my application to sleep for ten minutes. In order to prevent the application from freezing I have put the Sleep function in a loop, using a DoEvents, that exectutes 600,000 times, and I pass the Sleep function a value of 100 (m...
  2. IS there a sleep function in VB Script?
    IS there a sleep function in VB Script?
  3. sleep or wait function in VB
    Is there a way to code a sleep or wait function in VB?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: bruintjePosted on 2004-01-07 at 02:29:51ID: 10060530

Title : VB Sleep function
Source :

Description :
-----------
you could try this in a module

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub Command1_Click()
  Debug.Print "Started - " & Time()
  Sleep 1000
  Debug.Print "Ended - " & Time()
End Sub

Sleep will make the whole program wait for a amount of milliseconds
-----------

hope this helps a bit

 

by: ADSaundersPosted on 2004-01-07 at 02:37:45ID: 10060562

Hi shivermetimbers,
What exactly do you mean by 'sleep' VB is naturally interupt driven, that is it 'sleeps' until an event is fired that it is programmed to react to (form load, textbox change button click etc. etc.) Do you mean 'becomes un responsive' for 5 seconds, or does something every 5 seconds.
In either case, you need a timer.
In the first case, create a global boolean variable say IsActive
On Timer Tick, toggle it's value

in every other event check IsActive before doing anything.

If you want to do something every 5 seconds, set the timer interval to 5000 (ms) and carry out your processing in the timer tick event. N.B. It's usual to disable the timer in it's own event, and reset and enable it again at the end.

Regards .. Alan

 

by: inthedarkPosted on 2004-01-07 at 02:41:01ID: 10060575

Hi bruintje solution will work for 1 second. But there is a problem with sleep in that it can put your whole machine to sleep for 5 seconds, if windows is trying to send your app a message while the sleep is in progress. To avoide this create a sub for your delay.

Delay 5

Sub Delay(pdblSeconds As Double)

' delay for x secodns
' this sub used very little CPU resouces

Const OneSecond As Double = 1#/(1440# * 60#)

Dim dblWaitUntil As Date
dblWaitUntil = Now + OneSecond * pdblSeconds
Do Until Now>dblWaitUntil
    Sleep 100
    DoEvents ' Allow windows message to be processed
Loop

End Sub


 

by: inthedarkPosted on 2004-01-07 at 02:48:24ID: 10060598

As ADSaunders suggests say you are writing a windows service which wakes up every 30 seconds do check something if you use sleep 30000 and the operator tries to click on your systray icon the whole machine will feel like its has frozen until the sleep ends. But is you use the Delay sub, Delay 30 as described, your application will respond as soon as the icon is clicked and the user interface becomes active.  But the background task won't restart until the 30 seconds is up.

Hope this helps~)

 

by: DANNYMACPosted on 2004-01-27 at 20:51:25ID: 10215811

Add a .bas  module to your project
Name it mWait.bas
Paste all the code below into it and call it in your app

wait X: where x = seconds to delay

this will allow you app to wait but not be unresponsive of cause windows to "hang"

'******************
' Wait Module code
Option Explicit

Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

Private Const WAIT_ABANDONED& = &H80&
Private Const WAIT_ABANDONED_0& = &H80&
Private Const WAIT_FAILED& = -1&
Private Const WAIT_IO_COMPLETION& = &HC0&
Private Const WAIT_OBJECT_0& = 0
Private Const WAIT_OBJECT_1& = 1
Private Const WAIT_TIMEOUT& = &H102&

Private Const INFINITE = &HFFFF
Private Const ERROR_ALREADY_EXISTS = 183&

Private Const QS_HOTKEY& = &H80
Private Const QS_KEY& = &H1
Private Const QS_MOUSEBUTTON& = &H4
Private Const QS_MOUSEMOVE& = &H2
Private Const QS_PAINT& = &H20
Private Const QS_POSTMESSAGE& = &H8
Private Const QS_SENDMESSAGE& = &H40
Private Const QS_TIMER& = &H10
Private Const QS_MOUSE& = (QS_MOUSEMOVE _
                            Or QS_MOUSEBUTTON)
Private Const QS_INPUT& = (QS_MOUSE _
                            Or QS_KEY)
Private Const QS_ALLEVENTS& = (QS_INPUT _
                            Or QS_POSTMESSAGE _
                            Or QS_TIMER _
                            Or QS_PAINT _
                            Or QS_HOTKEY)
Private Const QS_ALLINPUT& = (QS_SENDMESSAGE _
                            Or QS_PAINT _
                            Or QS_TIMER _
                            Or QS_POSTMESSAGE _
                            Or QS_MOUSEBUTTON _
                            Or QS_MOUSEMOVE _
                            Or QS_HOTKEY _
                            Or QS_KEY)

Private Declare Function CreateWaitableTimer Lib "kernel32" _
    Alias "CreateWaitableTimerA" ( _
    ByVal lpSemaphoreAttributes As Long, _
    ByVal bManualReset As Long, _
    ByVal lpName As String) As Long
   
Private Declare Function OpenWaitableTimer Lib "kernel32" _
    Alias "OpenWaitableTimerA" ( _
    ByVal dwDesiredAccess As Long, _
    ByVal bInheritHandle As Long, _
    ByVal lpName As String) As Long
   
Private Declare Function SetWaitableTimer Lib "kernel32" ( _
    ByVal hTimer As Long, _
    lpDueTime As FILETIME, _
    ByVal lPeriod As Long, _
    ByVal pfnCompletionRoutine As Long, _
    ByVal lpArgToCompletionRoutine As Long, _
    ByVal fResume As Long) As Long
   
Private Declare Function CancelWaitableTimer Lib "kernel32" ( _
    ByVal hTimer As Long)
   
Private Declare Function CloseHandle Lib "kernel32" ( _
    ByVal hObject As Long) As Long
   
Private Declare Function WaitForSingleObject Lib "kernel32" ( _
    ByVal hHandle As Long, _
    ByVal dwMilliseconds As Long) As Long
   
Private Declare Function MsgWaitForMultipleObjects Lib "user32" ( _
    ByVal nCount As Long, _
    pHandles As Long, _
    ByVal fWaitAll As Long, _
    ByVal dwMilliseconds As Long, _
    ByVal dwWakeMask As Long) As Long

Public Sub Wait(lNumberOfSeconds As Long)
    Dim ft As FILETIME
    Dim lBusy As Long
    Dim lRet As Long
    Dim dblDelay As Double
    Dim dblDelayLow As Double
    Dim dblUnits As Double
    Dim hTimer As Long
   
    hTimer = CreateWaitableTimer(0, True, App.EXEName & "Timer")
   
    If Err.LastDllError = ERROR_ALREADY_EXISTS Then
        ' If the timer already exists, it does not hurt to open it
        ' as long as the person who is trying to open it has the
        ' proper access rights.
    Else
        ft.dwLowDateTime = -1
        ft.dwHighDateTime = -1
        lRet = SetWaitableTimer(hTimer, ft, 0, 0, 0, 0)
    End If
   
    ' Convert the Units to nanoseconds.
    dblUnits = CDbl(&H10000) * CDbl(&H10000)
    dblDelay = CDbl(lNumberOfSeconds) * 1000 * 10000
   
    ' By setting the high/low time to a negative number, it tells
    ' the Wait (in SetWaitableTimer) to use an offset time as
    ' opposed to a hardcoded time. If it were positive, it would
    ' try to convert the value to GMT.
    ft.dwHighDateTime = -CLng(dblDelay / dblUnits) - 1
    dblDelayLow = -dblUnits * (dblDelay / dblUnits - _
        Fix(dblDelay / dblUnits))
   
    If dblDelayLow < CDbl(&H80000000) Then
        ' &H80000000 is MAX_LONG, so you are just making sure
        ' that you don't overflow when you try to stick it into
        ' the FILETIME structure.
        dblDelayLow = dblUnits + dblDelayLow
    End If
   
    ft.dwLowDateTime = CLng(dblDelayLow)
    lRet = SetWaitableTimer(hTimer, ft, 0, 0, 0, False)
   
    Do
        ' QS_ALLINPUT means that MsgWaitForMultipleObjects will
        ' return every time the thread in which it is running gets
        ' a message. If you wanted to handle messages in here you could,
        ' but by calling Doevents you are letting DefWindowProc
        ' do its normal windows message handling---Like DDE, etc.
        lBusy = MsgWaitForMultipleObjects(1, hTimer, False, _
            INFINITE, QS_ALLINPUT&)
        DoEvents
    Loop Until lBusy = WAIT_OBJECT_0
   
    ' Close the handles when you are done with them.
    CloseHandle hTimer

End Sub


I am not sure where the code came from originally but it works great!
dan







 

by: JpmSoftPosted on 2004-02-26 at 10:13:33ID: 10462355

HEY DANNYMAC!
Thanks for this code!

I've been looking for something like this for years!

 

by: rabiaahPosted on 2004-04-17 at 06:26:29ID: 10849049

'We Need One CommandButton and A Regular Form :

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub cmdSleep_Click()
    Me.Caption = "Rabia Need the system to sleep 5 sec."
    'Sleep for 5000 ms
    Sleep 5000
    Me.Caption = ""
End Sub
Private Sub Form_Load()
    Me.Caption = ""
    cmdSleep.Caption = "Sleeping ..."
End Sub

'Code By : Rabia Abu-Hanna
'Nazareth - Israel

 

by: mengqingPosted on 2004-06-16 at 20:46:46ID: 11331320

Hi inthedark, i used ur code and it worked. but i have another problem now

i want the program while waiting for like 10 seconds, if a user event is found, say a click of a button, then the program will resume from delay and do wotever it has to do after, how do i do that? thx!!

 

by: mwardPosted on 2004-07-06 at 20:31:36ID: 11488063

I have included the following in my asp page ...

Delay 5

Sub Delay(pdblSeconds As Double)

' delay for x secodns
' this sub used very little CPU resouces

Const OneSecond As Double = 1#/(1440# * 60#)

Dim dblWaitUntil As Date
dblWaitUntil = Now + OneSecond * pdblSeconds
Do Until Now>dblWaitUntil
    Sleep 100
    DoEvents ' Allow windows message to be processed
Loop

End Sub

I get the following error, and have not been able to resolve it.  If you can help please do...

Microsoft VBScript compilation  error '800a03ee'

Expected ')'

/admin/DBMaint/DBDel2.asp, line 45

Sub Delay(pdblSeconds As Double)
----------------------^

 

by: joeschoePosted on 2004-08-10 at 16:55:02ID: 11768565

I tried DANNYMAC's code, I need such a routine badly.
Unfortunately it goes into an infinate loop.

I called it as follows:
Dim PauseTime As Long
PauseTime = 4
Wait (PauseTime)

but it just loops in the routine
    Do
        ' QS_ALLINPUT means that MsgWaitForMultipleObjects will
        ' return every time the thread in which it is running gets
        ' a message. If you wanted to handle messages in here you could,
        ' but by calling Doevents you are letting DefWindowProc
        ' do its normal windows message handling---Like DDE, etc.
        lBusy = MsgWaitForMultipleObjects(1, hTimer, False, _
            INFINITE, QS_ALLINPUT&)
        DoEvents
    Loop Until lBusy = WAIT_OBJECT_0

Is there a parameter I could change to make it finite?

 

by: RogueSolutionsPosted on 2004-10-27 at 07:53:21ID: 12422849

mengqing

To stop events being processed by your app set the Enable property to False (on any active forms) before calling the Delay sub.  Remember to set it True again after the Delay code completes (and in the case of an error occuring) or the user gets stuck.

 

by: ITKnightMarePosted on 2005-06-03 at 16:37:23ID: 14143959

HELL YEA! WAIT COMMAND IS AWSOME!

This will fix so many problems of mine.  :)) Thanks  DANNYMAC!  This isn't even my question thread but I think it helped me the most, lol.

 

by: BobDillil78Posted on 2005-06-24 at 10:21:23ID: 14295600

Wait stinks... This is by far the best "Pause" function Ive seen...


Private Declare Function GetTickCount Lib "kernel32" () As Long

Public Sub Pause(Seconds As Single)
   
  Dim T As Single
  Dim T2 As Single
  Dim Num As Single
 
  Num = Seconds * 1000
 
  T = GetTickCount()
  T2 = GetTickCount()
 
  Do Until T2 - T >= Num
    T2 = GetTickCount()
    DoEvents
  Loop
   
End Sub

 

by: abdulhameedsPosted on 2008-01-07 at 22:31:00ID: 20606406

first go to tool bar (add-ins) and select add-ins from the menu
it open small windows (load) vb6 API viewr
then open add-ins again select api viewr then press on it
it will open windows just select file--->load text file ----->WIN32API
you have to search for api ( sleep)

now open module
copy the code on the module


from any where you can wripte

sleep(1000)
msgbox"hi"
1000= 1 sec

module 
Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
 
 
form:
sub b1_click()
sleep(5000) 
msgbox"hi"
end sub 
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...