原文:https://cloud.tencent.com/developer/article/1030346
Castle是针对.NET平台的一个开源项目,从数据访问框架ORM到IOC容器,再到WEB层的MVC框架、AOP,基本包括了整个开发过程中的所有东西,为我们快速的构建企业级的应用程序提供了很好的服务.具体可参看TerryLee的Castle 开发系列文章。 可以通过称为 Facility 的组件用控制反转 (Inversion of Control, IoC) 和依赖注入将 第三方组件插入内核中。Startable Facility当一个组件满足一定的依赖关系之后,让它自动运行,比如说启动一个窗体或者启动某种服务。 Startable Facility的使用可以说是非常地简单,只要我们的组件实现了IStartable接口就可以了,关于Startable Facility具体可参看Castle IOC容器实践之Startable Facility(一)、Castle IOC容器实践之Startable Facility(二)。Quartz 是一个要与 Castle集成的大项目,因为它仅需要您用 Castle的生命周期来启动和停止它。这意味着,当 Castle启动时,您想要 Quartz 启动,当 Castle关闭时,您想要 Quartz 停止。
为了保持本示例的简单性,Quartz 配置使用 Quartz 发行版附带的默认值。这些默认值位于 quartz.properties 文件中,该文件是 dll 文件的一部分。要配置 Quartz 以将数据库用于持久层、远程调度和其他高级选项,必须创建自定义的 quartz.properties 文件。
Quartz 调度器易于启动和关闭;它只通过调用 StdSchedulerFactory.DefaultScheduler 来检索调度器对象。要启动 Quartz,执行 Scheduler.Start() 方法。要停止 Quartz,执行 Scheduler.Shutdown() 方法。要使 Quartz 的生命周期跟随 Castle,将 Start() 调用放入 IStartable的 Start() 方法中,并将 Shutdown() 调用放入 IStartable的 Stop() 方法中。清单 3 展示了添加 Quartz 代码之后完整的实现。
1: using Castle.Core;
2: using Quartz.Impl;
3: using Quartz;
4: using Common.Logging;
5: using System.Threading;
6:
7: namespace QuartzComponent
8: {
9: [Transient]
10: public class QuartzStartable : IStartable
11: {
12: private ISchedulerFactory _schedFactory;
13:
14: private static ILog log = LogManager.GetLogger(typeof(QuartzStartable));
15:
16: public QuartzStartable(ISchedulerFactory schedFactory)
17: {
18: _schedFactory = schedFactory;
19: }
20:
21: public void Start()
22: {
23: log.Info("Starting service");
24: IScheduler sched = _schedFactory.GetScheduler();
25:
26: log.Info("------- Scheduling Jobs ----------------");
27:
28: // jobs can be scheduled before sched.start() has been called
29:
30: // get a "nice round" time a few seconds in the future...
31: DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 15);
32:
33: // job1 will only fire once at date/time "ts"
34: JobDetail job = new JobDetail("job1", "group1", typeof(SimpleQuartzJob));
35: SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1");
36: // set its start up time
37: trigger.StartTime = ts;
38: // set the interval, how often the job should run (10 seconds here)
39: trigger.RepeatInterval = 10000;
40: // set the number of execution of this job, set to 10 times.
41: // It will run 10 time and exhaust.
42: trigger.RepeatCount = 100;
43:
44:
45: // schedule it to run!
46: DateTime ft = sched.ScheduleJob(job, trigger);
47: log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds",
48: job.FullName, ft.ToString("r"), trigger.RepeatCount, (trigger.RepeatInterval / 1000)));
49: log.Info