Windows服务+Quartz.net
App.config配置文件
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="JobList">
<section name="Job" type="Quartz入门Service.MyConfigHandler,Quartz入门Service"/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<JobList>
<Job>
<add key="Url" value="http://www.baidu.com"/>
<add key="Hour" value="10"/>
<add key="Minute" value="30"/>
</Job>
</JobList>
</configuration>
MyService.cs主服务程序:
public partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
SystemScheduler _systemScheduler = SystemScheduler.CreateInstance();
_systemScheduler.StartScheduler();
}
protected override void OnStart(string[] args)
{
SystemScheduler _systemScheduler = SystemScheduler.CreateInstance();
_systemScheduler.StartScheduler();
}
protected override void OnStop()
{
}
}
SystemScheduler.cs调度程序
public class SystemScheduler
{
private SystemScheduler()
{
}
public static SystemScheduler CreateInstance()
{
return new SystemScheduler();
}
private IScheduler _scheduler;
public void StartScheduler()
{
int hour = int.Parse(((NameValueCollection)ConfigurationManager.GetSection("JobList/Job"))["Hour"]);
int minute = int.Parse(((NameValueCollection)ConfigurationManager.GetSection("JobList/Job"))["Minute"]);
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler();
IJobDetail synchronousData = new JobDetailImpl("SynchronousData", typeof(SynchronousData));
ITrigger trigger =
TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule(
a => a.WithIntervalInHours(24).OnEveryDay().StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(hour, minute))).Build();
_scheduler.ScheduleJob(synchronousData, trigger);
_scheduler.Start();
}
public void StopScheduler()
{
_scheduler.Shutdown();
}
}
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();
}
}
}