posts - 176, comments - 240, trackbacks - 0, articles - 7

[导入]Quartz 任务调度

Posted on 2005-11-22 17:55 canonical 阅读(1083) 评论(0)  编辑  收藏 所属分类: 软件开发

quartz是一个高质量的任务调度软件包。其主要组成部分为:

Scheduler接口: quartz的执行线程,它根据Trigger决定调度时刻,根据JobDetail的说明实例化并运行Job

JobDetail类: 可持久化的任务描述信息。任务虽然分组,但是仅用作管理标示,任务之间并无实质性关联, 例如无法定义job chain。

Trigger类:任务的调度策略。这里的特点是调度策略与任务描述分开,调度策略和任务描述都可以分别在Scheduler注册,然后再关联起来。JobDetail与Trigger的关系是一对多。

JobDataMap: 将任务的运行时可持久化状态信息从JobDetail类中分离出来

Job接口: 任务的执行代码

StatefulJob接口: 无状态任务对应的JobDataMap可以认为是只读的,而有状态的任务在多次执行过程中保留对JobDataMap所作的修改,一个后果是有状态任务无法被并发执行。

JobExecutionException类: 可以通过JobExecutionException调整调度程序的下一步动作
Calendar接口: 用于从trigger的调度计划中排除某些时间段,例如假期等。

以上几个部分的交互关系如下:
class JobImpl implements Job{
    public void execute(JobExecutionContext context) throws JobExecutionException{
        JobDetail detail = context.getJobDetail();
        JobDataMap dataMap = detail.getJobDataMap();
        ...
    }
}

scheduler.addCalendar("myHolidays", holidayCalendar, false);
trigger.setCanlendarName("myHolidays");

JobDetail jobDetail = new JobDetail(jobName, jobGroupName, JobImpl.class);

scheduler.scheduleJob(jobDetail, trigger);

JobDetail可以设置如下属性:
1. Durability: non-durable的任务当不再与任何active trigger关联的时候将会从scheduler中被自动删除。
2. Volatility: volatile的任务在scheduler的两次启动之间不会被持久化
3. RequestsRecovery: 如果在执行过程中程序意外崩溃,标记为"request recovery"的任务在scheduler重起之后将会被再次执行,此时JobExecutionContext.isRecovering()返回true.

Trigger可以设置如下属性:
1. misfireInstruction: 设定当trigger错过了触发时刻的时候需要采取的处理策略

SimpleTrigger按照固定的时间间隔进行触发
startTime, endTime, repeatCount, repeatInterval

CronTrigger按照日历间隔进行触发
seconds minutes hours day-of-month month day-of-week

在quartz内部,QuartzSchedulerThread按照时间顺序选择trigger(没有任务优先级的概念), 然后在JobRunShell中运行Job。

JobRunShell中的调用顺序如下:

TriggerListener.triggerFired
    Called by the Scheduler when a Trigger has fired, and it's associated JobDetail is about to be executed.

TriggerListener.vetoJobExecution
    Called by the Scheduler when a Trigger has fired, and it's associated JobDetail is about to be executed.

JobListener.jobToBeExecuted
    Called by the Scheduler when a JobDetail is about to be executed (an associated Trigger has occured).

Job.execute
    Called by the Scheduler when a Trigger fires that is associated with the Job.
 
JobListener.jobWasExecuted
    Called by the Scheduler after a JobDetail has been executed, and be for the associated Trigger's triggered(xx) method has

been called.

Trigger.executionComplete
    Called after the Scheduler has executed the JobDetail associated with the Trigger in order to get the final instruction

code from the trigger.

TriggerListener.triggerComplete
     Called by the Scheduler when a Trigger has fired, it's associated JobDetail has been executed, and it's triggered(xx)

method has been called.

SchedulerListener.triggerFinalized [if(trigger.getNextFireTime() == null)]
     Called by the Scheduler when a Trigger has reached the condition in which it will never fire again.

只有注册用户登录后才能发表评论。


网站导航: