Quartz.net 사용 입문(3)
22905 단어 Quartz.NET 프레임
app.config 구성 파일
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
sectionGroup>
configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<arg key="configType" value="INLINE"/>
factoryAdapter>
logging>
common>
<log4net>
<appender name="InfoFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log/" />
<appendToFile value="true" />
<param name="DatePattern" value="yyyyMMdd.txt" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="1024KB" />
<staticLogFileName value="false" />
<Encoding value="UTF-8" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
layout>
appender>
<appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log/error.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="10240KB" />
<staticLogFileName value="true" />
<Encoding value="UTF-8" />
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="FATAL" />
filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
layout>
appender>
<root>
<level value="INFO" />
<appender-ref ref="InfoFileAppender" />
<appender-ref ref="ErrorFileAppender" />
root>
log4net>
<appSettings>
<add key="cron" value="* 5 * * * ?"/>
appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
startup>
configuration>
SyncDataService.cs 주 서비스 프로그램:
partial class SyncDataService : ServiceBase
{
private ILog logger;
private IScheduler scheduler;
//
private readonly string StrCron = ConfigurationManager.AppSettings["cron"] ?? "* 10 * * * ?";
///
///
///
public SyncDataService()
{
InitializeComponent();
//
logger = LogManager.GetLogger(this.GetType());
//
ISchedulerFactory factory = new StdSchedulerFactory();
//
scheduler = factory.GetScheduler();
}
///
///
///
///
protected override void OnStart(string[] args)
{
if (!scheduler.IsStarted)
{
//
scheduler.Start();
//
IJobDetail job = JobBuilder.Create().WithIdentity("AppLogJob", "AppLogJobGroup").Build();
//
ITrigger trigger = TriggerBuilder.Create().StartNow().WithCronSchedule(StrCron).Build();
//
scheduler.ScheduleJob(job, trigger);
logger.Info("Quarzt ");
}
}
///
///
///
protected override void OnStop()
{
if (!scheduler.IsShutdown)
{
scheduler.Shutdown();
}
}
///
///
///
protected override void OnPause()
{
scheduler.PauseAll();
base.OnPause();
}
///
///
///
protected override void OnContinue()
{
scheduler.ResumeAll();
base.OnContinue();
}
}
AppLogJob.cs作业:
///
/// applog
///
public class AppLogJob : IJob
{
// Common.Logging.dll
private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
///
///
///
///
public void Execute(IJobExecutionContext context)
{
try
{
logger.Info("AppLogJob ");
for (int i = 0; i < 10; i++)
{
logger.InfoFormat("AppLogJob {0}", i);
}
logger.Info("AppLogJob ");
}
catch (Exception ex)
{
logger.Error("AppLogJob ", ex);
}
}
}
Program.cs:
static class Program
{///
/// 。
///
static void Main(string[] args)
{
// s
if (args.Length > 0 && args[0] == "s")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new SyncDataService() };
ServiceBase.Run(ServicesToRun);
}
else
{
Console.WriteLine(" Windows ");
Console.WriteLine(" ,[1] [2] [3] ");
var rs = int.Parse(Console.ReadLine());
string strServiceName = "syncService[ ]";
switch (rs)
{
case 1:
// , "s" , windows
var path = Process.GetCurrentProcess().MainModule.FileName + " s";
Process.Start("sc", "create " + strServiceName + " binpath= \"" + path + "\" displayName= " + strServiceName + " start= auto");
Console.WriteLine(" ");
Console.Read();
break;
case 2:
Process.Start("sc", "delete " + strServiceName + "");
Console.WriteLine(" ");
Console.Read();
break;
case 3: break;
}
}
}
}
SynchronousData.cs同步数据
public class SynchronousData : IJob
{
public void Execute(IJobExecutionContext context)
{
string Url = ((NameValueCollection)ConfigurationSettings.GetConfig("JobList/Job"))["Url"];
WebClient wc = new WebClient();
WebRequest wr = WebRequest.Create(new Uri(Url));
using (StreamWriter sw = File.AppendText(@"d:\SchedulerService.txt"))
{
sw.WriteLine("------------------" + "MyService :" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + "------------------");
sw.Flush();
}
}
}