使用System.Threading的Timer&Quartz.net兩種方式實現定時執行任務,防止IIS釋放timer對象

   以前的一個項目中使用System.Threading.Timer對象時有沒有遇到IIS釋放Timer對象的問題。說實話以前真沒遇到過這個問題,就是說我以前定義的timer對象沒有釋放,運行正常,回來後我就百度尋找這方面得信息,原來IIS在運行WebApp時對於非靜態資源都是自動釋放,而我回頭看了看以前寫的Web程序,很幸運當時是這麼寫的:ide

Global.asax文件this

private static Timer time; //System.Threading;
private static Log log;
protected void Application_Start(object sender, EventArgs e)
{
    log = new Log();
    log.Write(ref time, 5000);
}

Log.cs內代碼:.net

class Log{   
        public void Write(ref Timer time,int flashTime)
        {
            if (time == null) {
                time = new Timer(new TimerCallback(DoExecution), this, 0, flashTime);
            }
        }
        void DoExecution(object obj)
        {
            //定時執行代碼
        }
}

也就是說把timer對象定義成全局靜態對象就不會被IIS所釋放,若是當時不這麼寫,確定會在出錯時鬱悶好一陣。不過如今知識面廣了,定時執行任務能夠使用Quartz.net開源組件,他封裝了Time對象,能夠使任務的執行更穩定,下面給出示例代碼:對象

public class TimeJob:Quartz.IJob {
    public void Execute(Quartz.JobExecutionContext context)
    {
        //須要定時執行的代碼。。。
    }
}
public class Global : System.Web.HttpApplication
{
    private static Timer time ;
    protected void Application_Start(object sender, EventArgs e)
    {
        //定義任務
        Quartz.JobDetail job = new Quartz.JobDetail("job1", "group1", typeof(TimeJob));
        //定義觸發器
        Quartz.Trigger trigger = Quartz.TriggerUtils.MakeSecondlyTrigger(5);//5秒執行
        trigger.Name = "trigger1";
        trigger.JobGroup = "group1";
        trigger.JobName = "job1";
        trigger.Group = "group1";
        //定義計劃着
        Quartz.ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();
        Quartz.IScheduler sch = sf.GetScheduler();
        sch.AddJob(job, true);//添加任務
        sch.ScheduleJob(trigger);//添加計劃者
        sch.Start();//開始執行
    }
}

以上代碼也是在Global.asax文件中定義的。資源


最後一向的做風:歡迎各位大牛拍磚~~~flash

相關文章
相關標籤/搜索