NET Timer 定时执行写日志任务解决方案

作者:袖梨 2022-06-25

一。使用Timer

Global.asax.cs代码:

引入命名空间:  System.IO;

 代码如下 复制代码

protected void Application_Start(object sender, EventArgs e)
{                    
            System.Timers.Timer myTimer = new System.Timers.Timer(10000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            myTimer.Interval = 10000;
            myTimer.Enabled = true; 

  }

 private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
               
            //指定日志文件的目录 
           string fileLogPath = AppDomain.CurrentDomain.BaseDirectory;
           string fileLogName = "LogProjectTest_" + DateTime.Now.ToLongDateString() + "_log.txt";
            /定义文件信息对象 
            FileInfo finfo = new FileInfo(fileLogPath + fileLogName);

            //创建只写文件流 
            using (FileStream fs = finfo.OpenWrite())
           {
               //根据上面创建的文件流创建写数据流 
                StreamWriter strwriter = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾 
               strwriter.BaseStream.Seek(0, SeekOrigin.End);
               //写入错误发生时间 
                strwriter.WriteLine("发生时间: " + DateTime.Now.ToString());
              //写入日志内容并换行 
                strwriter.WriteLine("错误内容: " + message); 
                strwriter.WriteLine("错误内容: ");
               //写入间隔符 
                strwriter.WriteLine("---------------------------------------------");
                strwriter.WriteLine();
                //清空缓冲区内容,并把缓冲区内容写入基础流 
               strwriter.Flush();
                //关闭写数据流 
                strwriter.Close();
                fs.Close();
           }
        } 

 二,使用Quartz.Net

 Quartz是一个Java开源的作业调度框架。官方网站:http://www.opensymphony.com/quartz/

IBM网站上有一篇简单易懂的文章:http://www.ibm.com/developerworks/cn/java/j-quartz/

Quartz.net是从java版本移植到.net版本的。官方网站:http://quartznet.sourceforge.net/

 

具体代码如下:

1.在项目添加引用:

  Quartz.dll

  Common.Logging.dll

2.创建一个普通类,实现Quartz.IJob接口

 

 代码如下 复制代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using System.IO;
namespace EMailShechelTest
{
    public class WriteLogJob:IJob
    {
        public void Execute(JobExecutionContext context)
        {
         
            string fileLogPath = AppDomain.CurrentDomain.BaseDirectory;
            string fileLogName = "LogProject_" + DateTime.Now.ToLongDateString() + "_log.txt";
      
            FileInfo finfo = new FileInfo(fileLogPath + fileLogName);

            //创建只写文件流 
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流 
                StreamWriter strwriter = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾 
                strwriter.BaseStream.Seek(0, SeekOrigin.End);
                //写入错误发生时间 
                strwriter.WriteLine("发生时间: " + DateTime.Now.ToString());
                //写入日志内容并换行 
                //strwriter.WriteLine("错误内容: " + message); 
                strwriter.WriteLine("错误内容: ");
                //写入间隔符 
                strwriter.WriteLine("---------------------------------------------");
                strwriter.WriteLine();
                //清空缓冲区内容,并把缓冲区内容写入基础流 
                strwriter.Flush();
                //关闭写数据流 
                strwriter.Close();
                fs.Close();
            }
        }

    }
}


 

3.定义一个执行任务调度的类

 

 代码如下 复制代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using Quartz.Impl;
namespace EMailShechelTest
{
    public   class WriteLogScheduler
    {
        static ISchedulerFactory _sf = new StdSchedulerFactory();
        static IScheduler _sched = _sf.GetScheduler();
       
        static WriteLogScheduler _instance=null;
        static object lockObj=new object ();

        public static WriteLogScheduler Instance
        {
            get
            {               
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                        {                         
                            _instance = new WriteLogScheduler();
                        }
                    }
                }
                return _instance;
            }
        }

        public void Start()
        {
            JobDetail job = new JobDetail("WriteLog", "Log", typeof(WriteLogJob));
            DateTime start = TriggerUtils.GetNextGivenSecondDate(null, 5);

            TimeSpan interval = TimeSpan.FromSeconds(10);
            Trigger trigger = new SimpleTrigger("WriteLog", "Log", "WriteLog", "Log", start, null, 10, interval);


            _sched.AddJob(job, true);
            DateTime dt = _sched.ScheduleJob(trigger);
            _sched.Start();
        }
        public void Stop()
        {
            _sched.Shutdown(true);
        }

    }
}


4.在Global.asax.cs代码

 

 

 代码如下 复制代码

protected void Application_Start(object sender, EventArgs e)
        {         

            WriteLogScheduler.Instance.Start();
        }

 

protected void Application_End(object sender, EventArgs e)
        {          
            WriteLogScheduler.Instance.Stop();
        }

相关文章

精彩推荐