原帖引自:https://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net
项目中有大量临时生成的文件,需要定时清理。原文定义为00:00时自动完成,改成了03:00进行自动任务。
Imports Quartz
Imports Quartz.Impl
Public Class JobScheduler
Public Shared Sub Start()
Dim scheduler As IScheduler = StdSchedulerFactory.GetDefaultScheduler()
scheduler.Start()
Dim job As IJobDetail = JobBuilder.Create(Of ScheduledTasks_Del_TempFiles)().Build()
Dim trigger As ITrigger = TriggerBuilder.Create().WithDailyTimeIntervalSchedule(Function(s) s.WithIntervalInHours(24).OnEveryDay().StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0))).Build()
scheduler.ScheduleJob(job, trigger)
End Sub
End Class
Imports System.IO
Imports Quartz
Imports Quartz.Impl
Public Class ScheduledTasks_Del_TempFiles
Implements IJob
Public Sub Execute(context As IJobExecutionContext) Implements IJob.Execute
'do something
Dim rootPath As String = HttpContext.Current.Server.MapPath("~/Temp/")
If IO.Directory.Exists(rootPath) Then
DeleteFilesFromFolder(rootPath)
End If
' Throw New NotImplementedException()
End Sub
Private Sub DeleteFilesFromFolder(Folder As String)
If Directory.Exists(Folder) Then
For Each _file As String In Directory.GetFiles(Folder)
File.Delete(_file)
Next
For Each _folder As String In Directory.GetDirectories(Folder)
DeleteFilesFromFolder(_folder)
Next
End If
End Sub
End Class
Global.asax
Imports System.Web.Optimization
Public Class MvcApplication
Inherits System.Web.HttpApplication
Protected Sub Application_Start()
AreaRegistration.RegisterAllAreas()
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
JobScheduler.Start()
End Sub
End Class