【问题标题】:Time loop for retrieving data from web - VB.NET从 Web 检索数据的时间循环 - VB.NET
【发布时间】:2014-11-25 00:23:22
【问题描述】:

我正在使用以下方法成功地从网络检索数据:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://www.example.org")
Dim o As Object

Dim dizi As String() = result.Split(New String() {",,,"}, StringSplitOptions.None)
' urls on the webpage are seperated with ,,, so it gets the first website
Dim urladdress As String = dizi(0)

o.Navigate2(urladdress)

但是,我需要为它添加时间循环。例如,它需要每 5 分钟检索一次数据。尝试了这个没有任何运气:

Imports System.Timers
Public Class TimerRequest
    Private Shared aTimer As Timer
    Private Shared o as Object
        Public Shared Sub Main()
             aTimer = New System.Timers.Timer(300000) ' 5 minutes
             AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
             aTimer.Enabled = True
        End Sub  
        Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)

'----------------------------------------

    Dim webClient As New System.Net.WebClient
    Dim result As String = webClient.DownloadString("http://www.example.org")
    Dim o As Object

    Dim dizi As String() = result.Split(New String() {",,,"}, StringSplitOptions.None)
    ' urls on the webpage are seperated with ,,, so it gets the first website
    Dim urladdress As String = dizi(0)

    o.Navigate2(urladdress)

'----------------------------------------

        End Sub  
 End Class  

这些是错误

![在此处输入图片描述][1]

这样做的正确方法是什么?

【问题讨论】:

  • without anyluck 是什么意思?它会崩溃吗?计时器会触发吗?

标签: .net vb.net visual-studio-2010


【解决方案1】:

我会使用 Microsoft 的响应式框架 (NuGet "Rx-Main") 来执行此操作。

这是您需要的全部代码:

Dim subscription = _
    Observable _
        .Interval(TimeSpan.FromMinutes(5.0)) _
        .StartWith(-1L) _
        .SelectMany( _
            Observable _
                .Using( _
                    Function() New WebClient(), _
                    Function(wc) _
                        wc.DownloadStringTaskAsync("http://www.example.org") _
                            .ToObservable())) _
        .Select(Function(result) _
            result.Split(New String() {",,,"}, StringSplitOptions.None)(0)) _
        .Subscribe(Sub(urladdress) o.Navigate2(urladdress))

这将自动下载您的页面并每 5 分钟解析一次urladdress

好消息是您可以致电subscription.Dispose() 关闭订阅。

【讨论】:

    【解决方案2】:

    您可以在循环中尝试 Sleep 方法吗?

    For i = 1 To 5 
    
    System.Threading.Thread.Sleep(300000) '// 5 mins in milliseconds
    
    '// Do Something
    
    Next i
    

    【讨论】:

    • 那只是睡觉。我希望它每 5 分钟检查/检索一次数据。
    • 查看编辑,我的意思是在循环中使用暂停 5 分钟
    • 它只会做 5 次,对吗?那么如何制作一个无限循环呢?
    • 无限循环通常是个坏主意,您应该进行某种测试来确定循环何时开始/停止,但如果您真的想要无限循环,只需将 For i = 1 To 5 更改为 @ 987654323@ 并将Next i 更改为Loop
    • 只需要添加这个,有一个无限函数会在那个'//做某事的地方运行。这还能用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多