How can i code this Vb.Net - vb.net

I have a function that needs to execute every 30 mins. How can I filter it using Today.Minute?
Here are the Codes I made.
Protected Sub mainLoop()
Dim Counting As Integer = 0
Try
While (Not stopping)
While Counting <> 2
If Today.Minute >= 0 Then
If Counting = 1 Then
ElseIf Counting = 0 Or Counting = 2 Then
PingServers()
Counting = Counting + 1
ElseIf Today.Minute >= 31 Then
If Counting = 1 Then
PingServers()
Counting = Counting + 1
ElseIf Counting = 0 Then
End If
End If
End While
If Counting = 2 Then
DoFunction()
End If
End While
Catch ex As Exception
End Try
End Sub
Please any one. Help :3

I guess something like this would do the trick:
Module StartupModule
Private _timer As Timers.Timer
Sub Main()
SetTimer(3000)
Console.ReadLine()
KillTimer()
End Sub
Private Sub SetTimer(interval As Double)
_timer = New Timers.Timer(interval)
AddHandler _timer.Elapsed, AddressOf OnTimedEvent
_timer.Start()
End Sub
Private Sub KillTimer()
_timer.Stop()
_timer.Dispose()
End Sub
Private Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
Console.WriteLine(DateTime.Now)
End Sub
End Module

Related

VB.Net Timer Tick

I have a few usercontrols that have timers on them (I've removed all but one to see if that was the issue), they are enabled and set to 1000ms intervals. The issue I am having is that each of the subs that I am calling within the timer are firing 5 times in a row before starting the count over. I even removed the If statements set the Timer interval to 60000 and only called one Sub. The problem still persisted.
Any help would be appreciated!
Interval set to 1000
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static j As Integer
Static i As Integer
'1 min Timer
If i >= 60 Then
popupmsg()
i = 0
Else
i = i + 1
End If
'15 Sec Timer
If j >= 15 Then
UpdateGrid()
j = 0
Else
j = j + 1
End If
End Sub
Interval set to 60000
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
popupmsg()
End Sub
Update with Sub Called
Public Sub popupmsg()
Dim dt As DataTable = Tbl_Mod_HaulerLoadsTableAdapter1.GetDataBy_spGetLastInsertedRowFromTbl_Mod_HaulerLoadsbyAssetID(iAssetID)
If dt.Rows.Count = 0 Then
Else
HaulerLoadID = dt.Rows(0).Item("HaulerLoadsID")
If iHaulsCount = 0 Then
iHaulsCount = HaulerLoadID
Else
If iHaulsCount < HaulerLoadID Then
If dt.Rows(0).Item("HaulerLoadsDispatched").ToString = "" Then
If dt.Rows(0).Item("HaulerLoadsLogOperator").ToString <> UserID Then
If frmMainNew.AcceptHaulAlert = True Then
iHaulsCount = HaulerLoadID
frmMainNew.AlertControl1.Images = frmMainNew.ImageList2.Images(1)
frmMainNew.AlertControl1.Show(frmMainNew, "Hauler", "There is a New Hauler Load Item", frmMainNew.ImageList2.Images(1))
End If
Else
End If
End If
Else
End If
iHaulsCount = HaulerLoadID
End If
End If
dt.Dispose()
End Sub
You don't have to use static, but Dim.
Static specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared.
i and j are initialised to 0 only once.

Change foreground color of TreeView node from a seperated Thread

With the following code I fill a Treeview with a root node and several child nodes in the MainForm LoadEvent. With the button btnPing I go through the nodes and search for child nodes with level 2. These nodes are then queried with My.computer.network.ping and the ForeColor of the ChildNode is colored according to the result red or green. The whole works synonymous. However, the GUI freezes me every time.
'### TreeView Test
Option Explicit On
Option Strict On
Public Partial Class MainForm
Public Sub New()
Me.InitializeComponent()
End Sub
'### Hauptprogramm wird geladen ###
Sub MainFormLoad(sender As Object, e As EventArgs)
'Treeview befüllen
With treeView1
.Nodes.Add("Test1")
.Nodes(0).Nodes.Add("Test1_a")
.Nodes(0).Nodes.Add("Test1_b")
.Nodes(0).Nodes.Add("Test1_c")
.Nodes(0).Nodes(0).Nodes.Add("10.23.59.1")
.Nodes(0).Nodes(1).Nodes.Add("10.23.59.90")
.Nodes(0).Nodes(1).Nodes.Add("10.23.59.90")
.Nodes(0).Nodes(2).Nodes.Add("10.23.59.10")
.Nodes(0).Nodes(2).Nodes.Add("10.23.59.11")
.Nodes(0).Nodes(2).Nodes.Add("10.23.59.12")
.Nodes(0).Nodes(2).Nodes.Add("10.23.59.13")
.Nodes(0).Nodes(2).Nodes.Add("10.23.59.14")
End With
'Treeview aufklappen
treeView1.ExpandAll
End Sub
'### Sub zum rekursiven durchsuchen der Nodes ###
Private Sub RecurseNodes(ByVal col As TreeNodeCollection)
For Each tn As TreeNode In col
If tn.Level = 2 Then
Try
If My.Computer.Network.Ping(tn.Text) Then
tn.ForeColor = Color.Green
tn.StateImageIndex= 4
Else
tn.ForeColor = Color.Red
tn.StateImageIndex=5
End If
Catch ex As Exception
tn.ForeColor = Color.Red
tn.StateImageIndex=5
End Try
End If
If tn.Nodes.Count > 0 Then
RecurseNodes(tn.Nodes)
End If
Next tn
End Sub
'### Button zum starten der rekursiven Suche ###
Sub BtnPingClick(sender As Object, e As EventArgs)
'Treeview rekursiv durchsuchen
RecurseNodes(treeView1.Nodes)
End Sub
End Class
Now I would like to convert the whole so that the Ping runs in a separate thread. Now I have only one understanding question about the process. Can I start a thread with parameter transfer? Then I would run through the list and start with each node with level 2 a thread and wait for feedback. How would the best approach be?
Best Regards
Kay
Here's another approach:
Sub BtnPingClick(sender As Object, e As EventArgs)
'Treeview rekursiv durchsuchen
RecurseNodes(TreeView1.Nodes)
End Sub
Private Async Sub RecurseNodes(ByVal col As TreeNodeCollection)
For Each tn As TreeNode In col
If tn.Level = 2 Then
Dim T As Task(Of Boolean) = Ping(tn.Text)
Await T
tn.ForeColor = If(T.Result, Color.Green, Color.Red)
tn.StateImageIndex = If(T.Result, 4, 5)
ElseIf tn.Nodes.Count > 0 Then
RecurseNodes(tn.Nodes)
End If
Next tn
End Sub
Private Function Ping(ByVal ip As String) As Task(Of Boolean)
Return Task.Factory.StartNew(Of Boolean)(
Function() As Boolean
Try
Return My.Computer.Network.Ping(ip)
Catch ex As Exception
Return False
End Try
End Function)
End Function
Some ideas...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim t As Task = Task.Run(Sub()
RecurseNodes(TreeView1.Nodes(0))
End Sub)
End Sub
Private Sub RecurseNodes(ByVal col As TreeNode)
For Each tn As TreeNode In col.Nodes
If tn.Level < 2 AndAlso tn.Nodes.Count > 0 Then
RecurseNodes(tn)
ElseIf tn.Level = 2 Then
Dim tp As Task
tp = Task.Run(Sub()
Dim c As Color
Dim idx As Integer
Try
If My.Computer.Network.Ping(tn.Text) Then
c = Color.Green
idx = 4
Else
c = Color.Red
idx = 5
End If
Catch ex As Exception
c = Color.Red
idx = 5
End Try
Me.Invoke(Sub()
tn.ForeColor = c
tn.StateImageIndex = idx
End Sub)
End Sub)
End If
Next tn
End Sub

background worker and threads

i am using a background worker with a timer to call a function that has a for loop... as below :
Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles t.Tick
t.Enabled = False
t.Interval = 5000
Start()
End Sub
Sub Start()
If frm10BckWorker.IsBusy <> True Then
frm10BckWorker.WorkerReportsProgress = True
frm10BckWorker.RunWorkerAsync()
End If
End Sub
Private Sub frm2BckWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles frm10BckWorker.DoWork
StartSending()
End Sub
Sub StartSending()
Try
f.GetNumbers("JK_SP_GET_Users_TO_PROCEED", UsersBulkCnx(8))
count = f.numbersTable.Rows.Count
If count = 0 Then Exit Sub
For I = 0 To count - 1
Id = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ID")))
MO = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("MO")))
FamilyName = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("FamilyName")))
CName = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ContactNAme")))
ImageUrl = Trim(f.GetReaderValue(f.numbersTable.Rows(I).Item("ImageUrl")))
If Not f.InsertUsers(MO, FamilyName, CName,UsersCnx(8)) Then
PROC = -1
End If
f.DeleteBulk(Id, BulkNbrCnx(8))
f.InsertHistory(MO, FamilyName, CName,ImageUrl, UsersBulkCnx(8))
Next
Catch ex As Exception
f.WriteToText("StartSending", ex.ToString)
End Try
End Sub
what i need is to run in background this function f.InsertHistory that i call in the for loop and keep the loop running at the time without waiting for this function to end to go to the next record in the loop,
any suggestions please?

Restricting SpinButtons to specific Min and Max values VBA

I am trying to restrict user to select value between a limit using SpinButton in VBA but its not working for me
Here is what I have tried
Private Sub UserForm_Initialize()
decimalSpin_Button.Min = 0
decimalSpin_Button.Max = 5
End Sub
Private Sub decimalSpin_Button_Change()
decimalPlaces_Value.Text = decimalSpin_Button.Value
End Sub
Private Sub decimalSpin_Button_SpinDown()
decimalPlaces_Value.Text = decimalPlaces_Value.Text - 1
End Sub
Private Sub decimalSpin_Button_SpinUp()
decimalPlaces_Value.Text = val(decimalPlaces_Value.Text) + 1
End Sub
You don't need the _SpinDown() and _SpinUp() This will do what you want
Private Sub UserForm_Initialize()
decimalSpin_Button.Min = 0
decimalSpin_Button.Max = 5
End Sub
Private Sub decimalSpin_Button_Change()
decimalPlaces_Value.Text = decimalSpin_Button.Value
End Sub

Issue with Progressbar in VB2012

I am trying to add a ProgressBar to my program. The program basically compares two values of time and when the values are equal a MessageBox appears to indicate that time is up. I need the ProgressBar to load based on the time difference of the two values. One of the values in a clock and the other is input by the user (similar to an alarm).
My code:
Imports System.Net.Mime.MediaTypeNames
Public Class Form1
Private hour As Integer = 0
Private minute As Integer = 0
Private second As Integer = 0
Public Sub show_time()
second += 1
If second = 59 Then
second = 0
minute += 1
If minute = 59 Then
minute += 1
hour += 1
End If
End If
Label3PrgressStdPC.Text = hour.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= minute.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= second.ToString.PadLeft(2, "0")
Label3PrgressStdPC.Refresh()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
show_time()
If TextBox1.SelectedText = TextBox1.Text Then Exit Sub
If TextBox1.Text = Label3PrgressStdPC.Text Then
Timer1.Stop()
MsgBox("time is up")
End If
End Sub
Private Sub Bn_start_St01_Click(sender As Object, e As EventArgs) Handles Bn_start_St01.Click
Timer1.Start()
Timer1.Enabled = True
Timer2.Start()
Timer2.Enabled = True
End Sub
**Private Sub ProgressBar1_Click(sender As Object, e As EventArgs) Handles ProgressBar1.Click
ProgressBar1.Maximum = , the max progrssbr will be determine by user input
ProgressBar1.Minimum = 0**
End Sub
**Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
progresbar1.value = ,Not so sure how to write the logic here**
End Sub
End Class
Can anyone help me out i am really getting frustrated.....thanks
How about something like this...
Private Ticker As Timer = New Timer 'Create a timer
Private Start As DateTime 'Store when we start
Private Expire As DateTime 'and when we end
'Call this to get things going
Sub Begin(EndHour As Integer, EndMinute As Integer, EndSecond As Integer)
Start = DateTime.Now
'If input is a time today ...
Expire = DateTime.Now.Date.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'or just a number of hours/mins/secs from now...
Expire = DateTime.Now.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'When the timer fires, call Tick()
AddHandler Ticker.Elapsed, Sub() Tick()
Ticker.Enabled = True
Ticker.Interval = 1000
Ticker.Start
End Sub
Private Sub Tick()
If DateTime.Now < Expire Then
'Not Finished
Dim Elapsed = DateTime.Now.Subtract(Start)
Dim TotalMillis = Expire.Subtract(Start).TotalMilliseconds
Dim ProgressDouble = Elapsed.TotalMilliseconds / TotalMillis
'Me.Invoke is used here as the timer Tick() occurs on a different thread to the
'one used to create the UI. This passes a message to the UI telling it to
'update the progress bar.
Me.Invoke(Sub()
ProgressBar1.Value = CInt(ProgressDouble * ProgressBar1.Maximum)
Label3PrgressStdPC.Text = Elapsed.ToString
End Sub)
Else
'Done
MessageBox.Show("Done")
Ticker.Stop
End If
End Sub
See VB.NET Delegates and Invoke - can somebody explain these to me? for more information on Invoking.