Java调度框架Quartz简单示例

Quartz的大名如雷贯耳,这里就不赘述,而且本文也不作为深入探讨,只是看完Quartz的官方文档后,下个简单示例,至少证明曾经花了点时间学习过,以备不时之需。

Quartz使用了SLF4J,所以至少你也知道如何配置日志,开发过程中最好把Quartz的日志打印出来,方便排查问题。先不详解直接上一个Demo.

项目结构如图:

log4j.properties

#log4j.logger.org.quartz=OFF
log4j.logger.org.quartz=INFO,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{mm:ss,SSS} %M %m%n

HelloJob.java

package net.oseye;

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

public class HelloJob implements Job{

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		System.out.println(arg0.getJobDetail().getKey().getName());
	}
}

App.java

package net.oseye;

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;
import org.quartz.impl.StdSchedulerFactory;

public class App {
	public static void main(String[] args) {
		JobDetail job = JobBuilder.newJob(HelloJob.class)
				.withIdentity("job1", "group1")
				.build();

		SchedulerFactory sf = new StdSchedulerFactory();
		try {
			Scheduler sched = sf.getScheduler();

			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity("trigger1", "group1")
					.startNow()
					.withSchedule(SimpleScheduleBuilder.simpleSchedule()
							.withIntervalInSeconds(10)
							.repeatForever())
					.build();
			sched.scheduleJob(job, trigger);
			sched.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}

执行后输出

48:17,734 instantiate Using default implementation for ThreadExecutor
48:17,859 initialize Job execution threads will use class loader of thread: main
48:17,921Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
48:17,921Quartz Scheduler v.2.2.1 created.
48:17,937 initialize RAMJobStore initialized.
48:17,937 initialize Scheduler meta-data: Quartz Scheduler (v2.2.1) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

48:17,937 instantiate Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
48:17,937 instantiate Quartz scheduler version: 2.2.1
48:17,968 start Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
job1

可以看出默认使用10个线程,使用的JobStor是RAM。

posted @ 2014-07-28 14:01  码农神说  阅读(422)  评论(0编辑  收藏  举报