SimpleJob的使用实例

quartz使用的是1.8.6版本
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SimpleJob implements Job {

	@Override
	public void execute(JobExecutionContext jobCtx)
			throws JobExecutionException {
		System.out.println(jobCtx.getTrigger().getName() +  " triggered.time.is:" + (new Date()));
	}
	
}

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerRunner {
	public static void main(String[] args) {
		try {
			//创建一个JobDdtail实例,指定SimpleJob,组名为jgroup1,名称为job1_1
			JobDetail jobDetail = new JobDetail("job1_1", "jgroup1", SimpleJob.class);
			
			//通过SimpleTrigger定义调度规则:马上启动,每2秒运行一次,共运行100次
			SimpleTrigger simpleTrigger = new SimpleTrigger("trigger1_1", "tgroup1");
			simpleTrigger.setStartTime(new Date());	//开始时间
			simpleTrigger.setRepeatInterval(2000);	//运行频率
			simpleTrigger.setRepeatCount(10);	//运行次数
			
			//通过SchedulerFactory获取一个调度器实例
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();
			
			//注册并进行调度
			scheduler.scheduleJob(jobDetail, simpleTrigger);
			//调度开始
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}

运行结果:
trigger1_1 triggered.time.is:Wed Apr 17 10:39:10 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:11 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:13 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:15 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:17 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:19 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:21 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:23 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:25 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:27 CST 2013
trigger1_1 triggered.time.is:Wed Apr 17 10:39:29 CST 2013
每次执行都是n+1条

其中注册代码也可以写成
simpleTrigger.setJobGroup("jgroup1"); //1.指定关联的Job组名
simpleTrigger.setJobName("job1_1"); //1.指定关联的Job名称
scheduler.addJob(jobDetail, true); //2.注册JobDetail
scheduler.scheduleJob(simpleTrigger); //3.注册指定了关联jobDetail的Trigger

1.2.3的顺序不能随意变动

你可能感兴趣的:(java,quartz,任务调度)