Task scheduling Quartz.Net the Windows Service

  This should be about Quartz.Net use the last article, before the introduction are Web-based, task scheduling way to achieve this is rare, because no matter MVC, WebApi or WebService, they all need lodging in IIS on the run, but we know that IIS will process the timing of the recovery pool, if the site has not received any requests, which will be recovered over a period of time until the next request restart automatically. If we need such a task at a fixed point execution time can not be guaranteed.

  Therefore, Windows Service task to achieve timing is more appropriate, which is scheduled by the operating system, we can set the service to from the start, it will start with the operating system and run the process.

  Create a Windows Service project, which will create a main entrance for us

static class Program
{
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    static void Main()
    {
        try
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
            new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }

    }
}

  We can start by Service1 the scheduled tasks, you can record the necessary log4net logs

public partial class Service1 : ServiceBase
{
    private Logger logger = new Logger(typeof(Service1));
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.logger.Info("This is OnStart..");

        IScheduler scheduler = await ScheduleManager.BuildScheduler();

        //使用配置文件
        XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
        await processor.ProcessFileAndScheduleJobs("~/config/quartz_jobs.config", scheduler);
        
    }

    protected override void OnStop()
    {
        this.logger.Info("This is OnStop..");
    }
}
<? xml Version = " 1.0 " encoding = " UTF-8 " ?> 
<log4net> 
    <-! the Define some the appenders in the Output -> 
    <appender name = " rollingAppender " of the type = " log4net.Appender.RollingFileAppender " > 
        <File = value " log \ log.txt " /> 

        <-! additional log contents -> 
        <appendToFile value = " to true " /> 

        <-! prevent multiple threads can not write log, the official said non-thread-safe -> 
        <lockingModel of the type = "log4net.Appender.FileAppender+MinimalLock"/> 

        <- can be:! Once | Size | Date | Composite -> 
        ! <- Composite is a combination of Size and Date -> 
        <rollingStyle value = " Composite " /> 

        <- When the backup file! for the file name plus the suffix -> 
        <datePattern value = " YYYYMMDD.txt " /> 

        <! - the maximum number of logs, are the latest -> 
        <! - when rollingStyle node as Size, only value log -> 
        ! <- rollingStyle node as Composite, there is value a daily log -> 
        <maxSizeRollBackups value = " 20 " /> 

        <- units available:! KB | MB | GB -> 
        < value = maximumFileSize " 3MB " />

        <! - set to true, the most current log file name is always the name of the section file -> 
        <staticLogFileName value = " to true " /> 

        <! - output level between INFO and ERROR logs -> 
        < type = filter " log4net.Filter.LevelRangeFilter " > 
            <param name = " LevelMin " value = " the INFO " /> 
            <param name = " LevelMax " value = " FATAL " /> 
        </ filter> 

        <layout type = " log4net. Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
        </layout>
    </appender>

    <!-- levels: OFF > FATAL > ERROR > WARN > INFO > DEBUG  > ALL -->
    <root>
        <priority value="ALL"/>
        <level value="ALL"/>
        <appender-ref ref="rollingAppender" />
    </root>
</log4net>
public class Logger
{
    static Logger()
    {
        XmlConfigurator.Configure(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config\\log4net.config")));
        ILog Log = LogManager.GetLogger(typeof(Logger));
        Log.Info("系统初始化Logger模块");
    }

    private ILog loger = null;
    public Logger(Type type)
    {
        loger = LogManager.GetLogger(type);
    }

    /// <summary>
    /// Log4日志
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="ex"></param>
    public void Error(string msg = "出现异常", Exception ex = null)
    {
        loger.Error(msg, ex);
    }

    /// <summary>
    /// Log4日志
    /// </summary>
    /// <param name="msg"></param>
    public void Warn(string msg)
    {
        loger.Warn(msg);
    }

    /// <summary>
    /// Log4日志
    /// </summary>
    /// <param name="msg"></param>
    public void Info(string msg)
    {
        loger.Info(msg);
    }

    /// <summary>
    /// Log4日志
    /// </summary>
    /// <param name="msg"></param>
    public void Debug(string msg)
    {
        loger.Debug(msg);
    }

}

  Finally, we can add right-install the program on the Service1 interface, to set up some information services.

 

 

 By then after the completion of the translation can install or uninstall the service by the following command

C: \ Windows \ Microsoft.NET \ Framework \ v4. 0.30319 \ InstallUtil QuartzProject.WindowsService.exe 


C: \ Windows \ Microsoft.NET \ Framework \ v4. 0.30319 \ InstallUtil / u QuartzProject.WindowsService.exe

 

Guess you like

Origin www.cnblogs.com/jesen1315/p/11653181.html