1、首先创建一个maven工程,在pom中引入quartz的依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
2、创建一个Hello World的Job类,实现quartz的Job接口就可以
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(new Date()));
System.out.println("This is hello job……");
}
}
3、测试,在测试方法中创建JobDetail、Trigger和Scheduler示例,并把JobDetail和Trigger绑定
public class App
{
public static void main( String[] args ) throws SchedulerException
{
/*创建JobDetail实例,并与HelloJob绑定;Job的名字是myjob,隶属于job_group组*/
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myjob", "job_group")
.build();
/*创建Trriger实例,指定Job每隔3秒钟执行一次*/
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("mytrigger", "trigger_group")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(3)
.repeatForever())
.build();
/*创建SchedulerFactory实例,把jobDetail与trigger绑定在一起*/
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
}
}
运行测试方法,输出
2018-04-01 16:40:41
This is hello job……
2018-04-01 16:40:43
This is hello job……
2018-04-01 16:40:46
This is hello job……
2018-04-01 16:40:49
This is hello job……
……
从日中可以看出,每三秒钟执行一次Hello World的Job。