一.准备
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
二.简单使用
HelloJob类
public class HelloJob implements Job {
public void execute(JobExecutionContext context) 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 World!");
}
}
HelloScheduler类
public class HelloScheduler {
public static void main(String[] args) {
//创建一个JobDetail实例,将该实例与HelloJob Class绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("myJob", "JobGroup1").build();
//创建一个Trigger实例,用来触发Job来执行的
//立即执行,并且每隔两秒执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "TriggerGroup1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2)
.repeatForever())
.build();
//创建scheduler实例,有很多工厂,这个是最简单的
SchedulerFactory sfact = new StdSchedulerFactory();
try {
Scheduler scheduler = sfact.getScheduler();
scheduler.start();
//打印当前的执行时间
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Exec Time is:" + sf.format(date));
scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
网友评论