使用VB.net自动执行任务

时间:2014-02-21 10:13:00

标签: vb.net windows backup scheduled-tasks

我有这个代码来自动备份文件夹,它可以很好地完成工作。然而,我希望通过每天下午12点自动备份来提升它。关于如何解决这个问题的Ant暗示将受到重视。

Imports System.IO
Imports System.IO.Compression
Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim dstr As String
    Dim mstr As String
    Dim ystr As String
    Dim folstr As String
    Dim dsumstr As String

    dstr = DateTime.Today.ToString("dd")
    mstr = DateTime.Today.ToString("MM")
    ystr = DateTime.Today.ToString("yyyy")
    dsumstr = ystr & "-" & mstr & "-" & dstr
    folstr = "Y:\server1\Fileserver-" & dsumstr
    Try
        My.Computer.FileSystem.CreateDirectory(folstr)

        My.Computer.FileSystem.CreateDirectory(folstr & "\SHARE-AC")
        My.Computer.FileSystem.CopyDirectory("D:\SHARE-AC", folstr & "\SHARE-AC")



        Label1.Text = "Back up DATE   " & dsumstr & "  Complete"
    Catch ex As Exception
        Label1.Text = (ex.Message)
    End Try

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Close()
End Sub
End Class

2 个答案:

答案 0 :(得分:2)

对于我们的Windows服务器,我们使用任务计划程序。您可以阅读更多here

enter image description here

答案 1 :(得分:0)

添加计时器 - 如下所示:

Dim WithEvents Timer1 As Timer

设置变量(或从任何地方读取)。

Dim runtimestring As String = "12:00 PM"
Dim nextruntime As Date

启动时将间隔设置为下一个运行时并启动计时器:

Sub New()
    'set up time interval
    If Now.TimeOfDay > Date.Parse(runtimestring).TimeOfDay Then
        'set nextruntime to tomorrow
        nextruntime = Date.Parse(runtimestring).AddDays(1)
    Else
        'set nextruntime to today
        nextruntime = Date.Parse(runtimestring)
    End If
    Timer1.Interval = nextruntime.Subtract(Now).TotalMilliseconds
    Timer1.Start()
End Sub

在Tick事件中,停止计时器根据需要执行你的函数/ subs,然后重新设置间隔并再次启动计时器。

Sub Timer1_Tick() Handles Timer1.Tick
    Timer1.Stop()
    'Add your functions and sub's here.....


    'set nextruntime to tomorrow
    nextruntime = Date.Parse(runtimestring).AddDays(1)
    Timer1.Interval = nextruntime.Subtract(Now).TotalMilliseconds
    Timer1.Start()
End Sub