189 8069 5689

使用System.Threading的Timer&Quartz.net两种方式实现定时执行任务,防止IIS释放timer对象

   之前的一个项目中使用System.Threading.Timer对象时有没有遇到IIS释放Timer对象的问题。说实话之前真没遇到过这个问题,就是说我之前定义的timer对象没有释放,运行正常,回来后我就百度寻找这方面得信息,原来IIS在运行WebApp时对于非静态资源都是自动释放,而我回头看了看之前写的Web程序,很幸运当时是这么写的:

成都创新互联是一家专业提供沙河口企业网站建设,专注与成都网站设计、成都网站建设、H5技术、小程序制作等业务。10年已为沙河口众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。

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文件中定义的。

最后一贯的作风:欢迎各位大牛拍砖~~~


新闻名称:使用System.Threading的Timer&Quartz.net两种方式实现定时执行任务,防止IIS释放timer对象
URL标题:http://cdxtjz.cn/article/pisdod.html

其他资讯