Quartz.net使用入门(三)
Windows服务,自定义安装,卸载服务+Quartz.net
app.config配置文件
<?xml version="1.0"?>
<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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
SyncDataService.cs主服务程序:
partial class SyncDataService : ServiceBase
{
private readonly ILog logger;
private IScheduler scheduler;
//时间间隔
private readonly string StrCron = ConfigurationManager.AppSettings["cron"] ?? "* 10 * * * ?";
/// <summary>
///构造函数
/// </summary>
public SyncDataService()
{
InitializeComponent();
//初始化
logger = LogManager.GetLogger(this.GetType());
//新建一个调度器工工厂
ISchedulerFactory factory = new StdSchedulerFactory();
//使用工厂生成一个调度器
scheduler = factory.GetScheduler();
}
/// <summary>
/// 服务开启
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
if (!scheduler.IsStarted)
{
//启动调度器
scheduler.Start();
//新建一个任务
IJobDetail job = JobBuilder.Create<AppLogJob>().WithIdentity("AppLogJob", "AppLogJobGroup").Build();
//新建一个触发器
ITrigger trigger = TriggerBuilder.Create().StartNow().WithCronSchedule(StrCron).Build();
//将任务与触发器关联起来放到调度器中
scheduler.ScheduleJob(job, trigger);
logger.Info("Quarzt 数据同步服务开启");
}
}
/// <summary>
/// 服务停止
/// </summary>
protected override void OnStop()
{
if (!scheduler.IsShutdown)
{
scheduler.Shutdown();
}
}
/// <summary>
/// 暂停
/// </summary>
protected override void OnPause()
{
scheduler.PauseAll();
base.OnPause();
}
/// <summary>
/// 继续
/// </summary>
protected override void OnContinue()
{
scheduler.ResumeAll();
base.OnContinue();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
AppLogJob.cs作业:
/// <summary>
/// 同步applog任务
/// </summary>
public class AppLogJob : IJob
{
//使用Common.Logging.dll日志接口实现日志记录
private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 定时任务执行
/// </summary>
/// <param name="context"></param>
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);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
Program.cs:
static class Program
{/// <summary>
/// 应用程序的主入口点。
/// </summary>
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;
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
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();
}
}
}