看完入门一程序,接下来接着讲解入门二.
JobDetail jobDetail = new JobDetail();
jobDetail.setJobClass(QuartzReport.class);
jobDetail.setName("MyJob_1");
jobDetail.setGroup("JobGroup_1");
1、创建JobDetial对象,设置工作项,这里有一个概念,JobClass,Name,Group.
上一讲的初始化程序为
public JobDetail(String name, String group, Class jobClass) {
setName(name);
setGroup(group);
setJobClass(jobClass);
}
创建JobDetail给定JobClass,Name,group,如果group为空,则组为Scheduler.DEFAULT_GROUP默认组.其实是一样的。
SimpleTrigger strigger = new SimpleTrigger();
strigger.setName("Trigger_1");
strigger.setGroup("Trigger_Group_1");
strigger.setStartTime(new Date());
2、创建Trigger对象 ,这是一个简单的Trigger对象,设置了name,group,startTime.
上一讲的初始化程序为
public CronTrigger(String name, String group) {
super(name, group);
setStartTime(new Date());
setTimeZone(TimeZone.getDefault());
}
创建CronTrigger给定名称和组,默认开始时间为当前时间.
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis() + 1000 * 1L);
strigger.setEndTime(c.getTime());
3. 设置重复停止时间,并销毁该Trigger对象,上一节没有停止时间
strigger.setRepeatInterval(1000 * 1L);
strigger.setRepeatCount(3);
4. 设置重复间隔时间,设置重复执行次数
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = sf.getScheduler();
scheduler.scheduleJob(jobDetail, strigger);
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
5、创建Scheduler对象,并配置JobDetail和Trigger对象.并开启
try {
scheduler.shutdown(true);
} catch (SchedulerException e) {
e.printStackTrace();
}
6. 关闭调度器
经过以上概念的分析和理解,大概已经知道了调度器需要任务详情,触发详情,任务启动,任务关闭,而任务详情包括任务类,任务名称,任务组,触发详情包括触发开始时间,触发结束时间,触发间隔时间,触发执行次数,任务的启动和中止等。
以下是总的例子
public class TestJob2 {
public static void main(String[] args) {
JobDetail jobDetail = new JobDetail();
jobDetail.setJobClass(QuartzReport.class);
jobDetail.setName("MyJob_1");
jobDetail.setGroup("JobGroup_1");
SimpleTrigger strigger = new SimpleTrigger();
strigger.setName("Trigger_1");
strigger.setGroup("Trigger_Group_1");
strigger.setStartTime(new Date());
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis() + 1000 * 1L);
strigger.setEndTime(c.getTime());
strigger.setRepeatInterval(100 * 1L);
strigger.setRepeatCount(100);
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = sf.getScheduler();
scheduler.scheduleJob(jobDetail, strigger);
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
try {
scheduler.shutdown(true);
} catch (SchedulerException e) {
e.printStackTrace();
}
}