quartz使用

准备工作
    
    建立Maven项目工程
    
    引入quartz jar包
    
编写第一个quartz任务
    
    让任务每隔两秒钟打印一次helloword

 

HelloJob.java

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{

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
//打印当前的执行时间 格式为2017-01-01 00:00:00
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Exec Time Is: " + sf.format(date));
// 编写具体的业务逻辑
System.out.println("hello quartz!");
}

}

HelloScheduler.java

import java.text.SimpleDateFormat;
import java.util.Date;

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 HelloScheduler {

public static void main(String[] args) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob Class绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob", "group1").build();

//创建一个Trigger实例,定义该job立即执行,并且每隔两秒钟执行一次
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1")
.startNow().withSchedule(
SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()
)
.build();

//创建Scheduler实例
SchedulerFactory sfact = new StdSchedulerFactory();
Scheduler scheduler = sfact.getScheduler();
scheduler.start();
//打印当前的时间 格式为2017-01-01 00:00:00
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Time Is: " + sf.format(date));
scheduler.scheduleJob(jobDetail,trigger);

}
}