项目中使用System.Threading.Timer对象时IIS释放Timer对象的问题2014-02-18 51cto tongling_zzu之前的一个项目中使用System.Threading.Timer对象时有没有遇到IIS释放Timer对象的问 题。说实话之前真没遇到过这个问题,就是说我之前定义的timer对象没有释放,运行正常, 回来后我就百度寻找这方面得信息,原来IIS在运行WebApp时对于非静态资源都是自动释放, 而我回头看了看之前写的Web程序,很幸运当时是这么写的:Global.asax文件
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内代码:
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文件中定义的。