定义一个继承Jop的任务HelloJob,实现execute方法
package com.esafenet.ta.da.reoortriskrule.listener;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class HelloJob implements Job{
@Override
public void execute(JobExecutionContext Context) throws JobExecutionException {
JobKey jk = Context.getJobDetail().getKey();//获取jobdetail和触发器的withIdentity
JobDataMap jmap = Context.getJobDetail().getJobDataMap();//获取jsbdetail的usingJobData设置的key value 的集合 map
System.out.println("HelloJob--HelloJob:"+jmap.getString("lover")+"---"+jmap.getFloatValue("floatvalue"));
System.out.println(jk);
}
}
在使用Scheduler之前,需要实例化(谁猜到了?)。为此,您可以使用SchedulerFactory。Quartz的一些用户可能会在JNDI存储中保留factory的实例,其他用户可能会发现直接初始化会更加简单(例如下面的示例)。
scheduler实例化后,可以启动(start)、暂停(stand-by)、停止(shutdown)。注意:scheduler被停止后,除非重新实例化,否则不能重新启动;只有当scheduler启动后,即使处于暂停状态也不行,trigger才会被触发(job才会被执行)。
下面的代码片段,实例化并启动一个scheduler,调度执行一个job:
package com.esafenet.ta.da.reoortriskrule.listener;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
public class QuartzJob {
public static void go() throws SchedulerException{
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
JobDetail job = JobBuilder
.newJob(HelloJob.class)
.usingJobData("lover", "xcl")
.usingJobData("floatvalue", 3.1415f)
.withIdentity("job1","group1")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("job1","group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1)).startNow().build();
sched.scheduleJob(job, trigger);
if(!sched.isShutdown()){
sched.start();
}
}
public static void main(String[] args) throws SchedulerException {
go();
}
}