主题:sleep?timer控件都不行,还有什么好延时函数吗
smart200
[专家分:20] 发布于 2008-06-24 14:50:00
程序规定2个小时刷新一次,要求在这4个小时中还可以点其他按钮,
用sleep发现的问题:
1。sleep(4小时),程序直接死机,用doevents也不能中断。
2。timer控件时间间隔太短,只有1分多钟就自己响应一次。
有什么其他办法吗
回复列表 (共5个回复)
沙发
tanchuhan [专家分:15140] 发布于 2008-06-24 16:14:00
把Timer的Interval属性设为60000(1分钟)
Private Sub Timer1_Timer()
Static i As Long
i = i + 1
If i = 2 * 60 Then
i = 0
'do something here
End If
End Sub
板凳
老大徒伤悲 [专家分:29120] 发布于 2008-06-24 20:28:00
在计时开始,记录时间:
t=now
然后
do
doevents
loop until now-t>1/12
‘刷新
3 楼
tanchuhan [专家分:15140] 发布于 2008-06-25 02:38:00
[quote]在计时开始,记录时间:
t=now
然后
do
doevents
loop until now-t>1/12
‘刷新[/quote]
这样会把代码一直“卡在”这个Do ... Loop里面2小时
虽然DoEvents的调用可以让消息循环正常运作,但这样等于自己另外建一个消息循环来PeekMessage消息队阵里面的消息。
还会引起一些副作用,例如窗体的关闭按钮被点击后,程序并不会退出。
(另外还有一种效应,好像叫代码重入)
所以DoEvents循环并不适合“长间隔”延时。
4 楼
smart200 [专家分:20] 发布于 2008-06-25 11:29:00
Public Sub delay(ByVal n As Single) '设计延时函数,n表示需要延时的秒数
Dim tm1 As Single, tm2 As Single
tm1 = Timer '返回一个 Single,代表从午夜开始到现在经过的秒数。
Do
tm2 = Timer '如果tm2<tm1,说明tm1恰好在午夜前,而tm2在午夜后,相差24小时
If tm2 < tm1 Then tm2 = tm2 + 86400
If tm2 - tm1 > n Then Exit Do
DoEvents 'DoEvents 会将控制权传给操作系统。
Loop
End Sub
5 楼
snyga [专家分:1480] 发布于 2008-06-27 22:56:00
Private Declare Function GetMS Lib "winmm.dll" Alias "timeGetTime" () As Long
Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
'调用: Delay 5000 延时5秒
Public Sub Delay(DelayTime As Long)
Dim k As Long
k = GetMS
Do Until GetMS - k >= DelayTime
Sleep 1
DoEvents
Loop
End Sub
我来回复