跳到主要內容

[Asp.net] 在asp.net中加入排程功能

在web的程式中
通常程式要被觸發 是要有使用者進入該網址才會有
但如果想要website的程式在某個時間可以執行某個程序
可以把在Global.asax中 加入Threading.Timer
這樣可以設定在Application啟動後 每隔一段時間去執行某個程序
而不需要有使用者登入web才觸發行為

用法如下


imports System.Web.SessionState
Imports System.Threading
Imports System.IO
Public Class Global_asax
    Inherits System.Web.HttpApplication
    Dim logTimer As Timer

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started
        Dim are As New AutoResetEvent(False)
        Dim tcb As New TimerCallback(AddressOf writelog)
        logTimer = New Timer(tcb, are, 10000, 60000)
    End Sub
    '在系統資料夾下寫入log
    Public Sub writelog()
        '系統程式的路徑
        Dim u As String = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath()
        Dim filePath As String = u & Now.ToString("yyyyMMdd") & "log.txt"
        Application("test") = filePath & " @" & Now.ToString()
        Dim sw As New StreamWriter(filePath, True)
        Application("test2") = "W succsee"
        sw.WriteLine(Now)
        sw.Close()
    End Sub

End Class

留言