源代碼地址: https://github.com/fluentscheduler/FluentScheduler
使用NuGet安裝FluentScheduler
這是我實際項目中用到的代碼,也可看此博主的文章http://www.cnblogs.com/mafly/p/FluentScheduler.html
在Controller中寫
public class TimedTask : IJob, IRegisteredObject { private readonly object _lock = new object(); private bool _shuttingDown; public Registry Start() { HostingEnvironment.RegisterObject(this); Registry registry = new Registry();
//每天幾點執行一次代碼 registry.Schedule(() => Execute()).ToRunEvery(1).Days().At(01,00); return registry; } public void Execute() {lock (_lock) { if (_shuttingDown) { return; } else { //這里寫每天固定時間要運行的代碼 } } } public void Stop(bool immediate) { lock (_lock) { _shuttingDown = true; } HostingEnvironment.UnregisterObject(this); } }
在Global.asax中寫
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { //定時任務 TimedTask timedtask = new TimedTask(); JobManager.Initialize(timedtask.Start()); } }