工程结构:
nospring包下的两个类用于非spring环境下的quartz demo演示
springenv包下的两个类用于spring环境下的quartz demo演示
不多BB了,我上来就先贴个POM.XML,因为我不写跑不起来的东西,跑不起来我写这博客误人子弟作甚?
pom.xml :
4.0.0 com.chenjun QtzTest 1.0 jar QtzTest http://maven.apache.org UTF-8 3.1.4.RELEASE 1.7.7 1.1.7 org.springframework spring-context ${springframework.version} org.springframework spring-context-support ${springframework.version} org.springframework spring-tx ${springframework.version} org.springframework spring-web ${springframework.version} org.quartz-scheduler quartz 1.8.6 org.slf4j slf4j-api ${slf4j.version} org.slf4j slf4j-log4j12 ${slf4j.version} ch.qos.logback logback-classic ${logback-classic.version} test org.slf4j jcl-over-slf4j ${slf4j.version} org.slf4j jul-to-slf4j ${slf4j.version} junit junit 3.8.1 test ${project.artifactId} org.mortbay.jetty jetty-maven-plugin 7.5.4.v20111024 10 /${project.artifactId}
(一)非spring环境下
1、新建一个MyJob.JAVA
import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.StatefulJob;public class MyJob implements StatefulJob{ public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("触发!"); }}
2、新建一个MySchedule.java
import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SchedulerFactory;import org.quartz.Trigger;import org.quartz.TriggerUtils;import org.quartz.impl.StdSchedulerFactory;/** * Hello world! */public class MySchedule{ public static void main(String[] args) { SchedulerFactory factory=new StdSchedulerFactory(); Scheduler scheduler; try { //调度器 scheduler = factory.getScheduler(); scheduler.start(); //job详细 JobDetail jobDetail = new JobDetail("MyJob",null, MyJob.class); //触发器 Trigger trigger = TriggerUtils.makeSecondlyTrigger(1); trigger.setName("MyTrigger"); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { e.printStackTrace(); } }}
MySchedule.JAVA 右键->运行
跑一下,每秒钟输出~~~ 如下图
(二)spring环境下 :
1、新建一个类SimpleJob.java:
import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.scheduling.quartz.QuartzJobBean;public class SimpleJob extends QuartzJobBean{ @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { String message = context.getJobDetail().getJobDataMap().getString("message"); System.out.println(message); }}
2、新建一个类SimpleSpringQuartz.java
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SimpleSpringQuartz{ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml"); }}
3。新建logback.XML:
%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n /tmp/logs/myspring.log /tmp/logs/ty.%d{yyyy-MM-dd HH:mm:ss.SSS}.log %date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
4。新建spring.XML
Spring环境下 输出结果:如下图: