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

推荐订阅源

S
SegmentFault 最新的问题
Spread Privacy
Spread Privacy
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
SecWiki News
SecWiki News
腾讯CDC
P
Privacy International News Feed
Webroot Blog
Webroot Blog
J
Java Code Geeks
爱范儿
爱范儿
A
About on SuperTechFans
S
Secure Thoughts
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
DataBreaches.Net
Cloudbric
Cloudbric
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Security Latest
Security Latest
Forbes - Security
Forbes - Security
小众软件
小众软件
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Cybersecurity and Infrastructure Security Agency CISA
T
Threatpost
量子位
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
W
WeLiveSecurity
P
Privacy & Cybersecurity Law Blog
Vercel News
Vercel News
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
The Exploit Database - CXSecurity.com
Help Net Security
Help Net Security
V
Visual Studio Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 聂微东
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs

博客园 - 笑傲江湖

客户端使用自定义代理类访问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();
        }