惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
S
Securelist
MyScale Blog
MyScale Blog
Jina AI
Jina AI
罗磊的独立博客
The Cloudflare Blog
美团技术团队
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
雷峰网
雷峰网
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
博客园 - 聂微东
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
T
Tailwind CSS Blog
Attack and Defense Labs
Attack and Defense Labs
博客园_首页
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Hacker News
The Hacker News
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
D
Docker
Webroot Blog
Webroot Blog
N
Netflix TechBlog - Medium
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
The Last Watchdog
The Last Watchdog
B
Blog
Recent Announcements
Recent Announcements
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Security Latest
Security Latest
V2EX - 技术
V2EX - 技术
N
News | PayPal Newsroom
Microsoft Security Blog
Microsoft Security Blog

博客园 - 笑傲江湖

客户端使用自定义代理类访问WCF服务 用户中心 - 博客园 用户中心 - 博客园 任意类型转换成json ASP.net中动态加载控件时一些问题的总结 图片等比例显示 用select做下拉式友情链接及jquery改写 - 笑傲江湖 - 博客园 一个商城的购车相关代码 M| SQL 导入导出的时候数据库表的主键和自动编号丢失 怎么办 .Net通用分页类 存储过程分页 鼠标经过时改变背景颜色 - 笑傲江湖 - 博客园 GridView、Repeater等数据控件列数字、货币和日期的显示格式 - 笑傲江湖 - 博客园 【JQuery】鼠标经过表格行变色 - 笑傲江湖 - 博客园 ASP实现长文章自动分页的函数代码 - 笑傲江湖 - 博客园 JQuery图片大小自适应 - 笑傲江湖 - 博客园 Visual Studio小技巧:复制代码时,保留原ID eWebEditor编辑器 IE8.0兼容 一个简单的XML的操纵类 asp.net日期格式
.NET 定时执行写日志任务解决方案(Timer & Quartz.Net)
笑傲江湖 · 2011-10-26 · via 博客园 - 笑傲江湖

共有两种方法:

一。使用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();
        }