慕课网:https://www.imooc.com/learn/841、https://www.imooc.com/learn/846
基于给定的时间点,给定的时间间隔或者给定的执行次数自动执行的任务
Timer
Quartz
Timer
能完成一些简单的定时任务,能实现具体某个时间执行任务。只有一个后台执行定时任务。
Quartz
能实现更复杂的定时任务,比如每个星期、月份执行的定时任务。能通过后台线程池来执行定时任务。
有且仅有一个后台线程对多个业务线程进行定时定频率的调度。
MyTimerTask.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;
/**
* Created by PengHongfu 2018-09-04 11:10
*/
public class MyTimerTask extends TimerTask {
private String name;
private Integer count = 0;
public MyTimerTask(String inputName) {
name = inputName;
}
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current exec time is: " + sf.format(calendar.getTime()));
System.out.println("Current exec name is: " + name);
count++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MyTimer.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
/**
* Created by PengHongfu 2018-09-04 11:13
*/
public class MyTimer {
public static void main(String args[]){
//1.创建一个timer实例
Timer timer = new Timer();
//2.创建一个MyTimerTask实例
MyTimerTask myTimerTask = new MyTimerTask("NO.1");
//3.通过timer定时定频率调用mytimertask的业务逻辑
//即第一次执行是在当前时间两秒之后,之后每隔一秒钟执行一次
timer.schedule(myTimerTask,2000L,1000L);
}
}
schedule()、scheduleAtFixedRate()
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
/**
* Created by PengHongfu 2018-09-04 11:13
*/
public class MyTimer {
public static void main(String args[]) {
//1.创建一个timer实例
Timer timer = new Timer();
//2.创建一个MyTimerTask实例
MyTimerTask myTimerTask = new MyTimerTask("NO.1");
//3.通过timer定时定频率调用mytimertask的业务逻辑
//即第一次执行是在当前时间两秒之后,之后每隔一秒钟执行一次
//timer.schedule(myTimerTask,2000L,1000L);
/**
* --------------- schedule用法 ---------------
*/
/**
* 用法一.schedule(task,time) 在当前时间等于或者超过time时执行一次task
*/
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sf.format(calendar.getTime()));
calendar.add(Calendar.SECOND, 3);//3s之后的时间
//myTimerTask.setName("schedule1");
//timer.schedule(myTimerTask,calendar.getTime());
/**
* 用法二.schedule(task,time,period) 在当前时间等于或者超过time时执行一次task,之后每隔period重复执行task
*/
//myTimerTask.setName("schedule2");
//timer.schedule(myTimerTask,calendar.getTime(),2000L);
/**
* 用法三.schedule(task,delay) 等待delay毫秒后执行且仅仅执行一次task
*/
//myTimerTask.setName("schedule3");
//timer.schedule(myTimerTask,2000L);
/**
* 用法四.schedule(task,delay,period) 等待delay毫秒后执行且仅仅执行task,之后每隔period执行一次
*/
//myTimerTask.setName("schedule4");
//timer.schedule(myTimerTask,3000L,3000L);
/**
* ---------------------- scheduleAtFixedRate用法 ----------------------
*/
/**
* 用法一:scheduleAtFixedRate(TimerTask task, long delay, long period)
*/
//myTimerTask.setName("scheduleAtFixedRate1");
//timer.scheduleAtFixedRate(myTimerTask,2000L,2000L);
/**
* 用法二:scheduleAtFixedRate(TimerTask task, Date firstTime,long period)
*/
//myTimerTask.setName("scheduleAtFixedRate2");
//timer.scheduleAtFixedRate(myTimerTask,calendar.getTime(),2000L);
/**
* ---------------------- scheduledExecutionTime方法 ----------------------
* 返回此任务最近实际执行的已安排执行的时间
*/
myTimerTask.setName("schedule");
timer.schedule(myTimerTask, 2000L);
System.out.println("scheduled time is:" + sf.format(myTimerTask.scheduledExecutionTime()));
}
}
cancel()
方法
TimerTask
中的cancel()
方法,取消当前类中的任务
Timer
中的方法cancel()
方法,取消其调度下的所有任务。
*/
public class MyTimerTask extends TimerTask {
private String name;
private Integer count = 0;
public MyTimerTask(String inputName){
name = inputName;
}
@Override
public void run() {
if(count < 3) {//执行三次之后取消执行
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current exec time is: " + sf.format(calendar.getTime()));
System.out.println("Current exec name is: " + name);
count++;
}else{
cancel();//终止执行
System.out.println("Task cancel");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CancelTest.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
/**
* cancel()方法
* Created by PengHongfu 2018-09-04 16:30
*/
public class CancelTest {
public static void main(String args[]) throws InterruptedException {
Timer timer = new Timer();
MyTimerTask task1 = new MyTimerTask("task1");
MyTimerTask task2 = new MyTimerTask("task2");
Date startTime = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("start time is:" + sf.format(startTime));
timer.schedule(task1, 3000, 2000);
timer.schedule(task2, 1000, 2000);
//休眠5秒
Thread.sleep(5000);
Date cancelTime = new Date();
System.out.println("cancel time is:" + sf.format(cancelTime));
//取消所有任务
timer.cancel();
System.out.println("Tasks all canceled!");
}
}
scheduledExecutionTime()
方法返回此任务最近实际执行的已安排执行的时间
/**
* ---------------------- scheduledExecutionTime方法 ----------------------
* 返回此任务最近实际执行的已安排执行的时间
*/
myTimerTask.setName("schedule");
timer.schedule(myTimerTask, 2000L);
System.out.println("scheduled time is:" + sf.format(myTimerTask.scheduledExecutionTime()));
主要在于
* 首次计划执行的时间早于当前的时间
* 任务执行所需时间超出任务的执行周期间隔
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
/**
* 计划时间早于当前时间
* Created by PengHongfu 2018-09-04 16:58
*/
public class DifferenceTest {
public static void main(String args[]) {
Timer timer = new Timer();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("start time is:" + sf.format(calendar.getTime()));
calendar.add(Calendar.SECOND, -6);//时间设置为6秒前
//测试两个方法 在首次计划执行时间早于当前时间的运行情况
//timer.schedule...
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Schedule exec time is:" + sf.format(scheduledExecutionTime()));
System.out.println("Task isbeing executed");
}
}, calendar.getTime(), 2000);
}
}
schedule:
start time is:2018-09-06 11:01:09
Schedule exec time is:2018-09-06 11:01:09
Task isbeing executed
Schedule exec time is:2018-09-06 11:01:11
Task isbeing executed
Schedule exec time is:2018-09-06 11:01:13
Task isbeing executed
scheduleAtFixedRate:
start time is:2018-09-06 10:57:25
Schedule exec time is:2018-09-06 10:57:19
Task isbeing executed
Schedule exec time is:2018-09-06 10:57:21
Task isbeing executed
Schedule exec time is:2018-09-06 10:57:23
Task isbeing executed
public static void main(String args[]) {
Timer timer = new Timer();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("start time is:" + sf.format(calendar.getTime()));
//执行间隔为2s,执行时间消耗4s
//timer.schedule....
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Schedule exec time is:" + sf.format(scheduledExecutionTime()));
System.out.println("Task isbeing executed");
}
}, calendar.getTime(), 2000);
}
schedule:
start time is:2018-09-06 11:07:54
Schedule exec time is:2018-09-06 11:07:54
Task isbeing executed
Schedule exec time is:2018-09-06 11:07:58
Task isbeing executed
Schedule exec time is:2018-09-06 11:08:02
Task isbeing executed
Schedule exec time is:2018-09-06 11:08:06
scheduleAtFixedRate:
start time is:2018-09-06 11:04:27
Schedule exec time is:2018-09-06 11:04:27
Task isbeing executed
Schedule exec time is:2018-09-06 11:04:29
Task isbeing executed
Schedule exec time is:2018-09-06 11:04:31
Task isbeing executed
import java.text.SimpleDateFormat;
import java.util.TimerTask;
/**
* 跳舞机器人
* Created by PengHongfu 2018-09-04 17:16
*/
public class DancingRobot extends TimerTask {
@Override
public void run() {
//获取最近的一次执行任务的时间
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Schedule exec time is:"+sf.format(scheduledExecutionTime()));
System.out.println("Dancing......");
}
}
WaterRobot.java
import java.util.Timer;
import java.util.TimerTask;
/**
* 灌水机器人
* Created by PengHongfu 2018-09-04 17:20
*/
public class WaterRobot extends TimerTask {
private Timer timer;
//最大容量为5L
private Integer bucketCapacity = 0;
public WaterRobot(Timer timer) {
this.timer = timer;
}
@Override
public void run() {
//灌水直至桶满
if (bucketCapacity < 5) {
System.out.println("Add 1L Water into the bucket!");
bucketCapacity++;
} else {
//水满取消执行
cancel();
System.out.println("The waterRobot has been aborted");
//timer终止的任务数
System.out.println("The number of canceled task:" + timer.purge());
System.out.println("Current water is:" + bucketCapacity);
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("all task has been aborted!");
}
}
}
Executor.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
/**
* Created by PengHongfu 2018-09-04 17:24
*/
public class Executor {
public static void main(String args[]){
Timer timer = new Timer();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current time is:" + sf.format(calendar.getTime()));
DancingRobot dr = new DancingRobot();
WaterRobot wr = new WaterRobot(timer);
timer.schedule(dr,calendar.getTime(),2000);
timer.schedule(wr,calendar.getTime(),1000);
}
}
Current time is:2018-09-06 11:30:27
Schedule exec time is:2018-09-06 11:30:27
Dancing......
Add 1L Water into the bucket!
Add 1L Water into the bucket!
Schedule exec time is:2018-09-06 11:30:29
Dancing......
Add 1L Water into the bucket!
Add 1L Water into the bucket!
Schedule exec time is:2018-09-06 11:30:31
Dancing......
Add 1L Water into the bucket!
The waterRobot has been aborted
The number of canceled task:1
Current water is:5
all task has been aborted!
Timer有且仅有一个线程去执行定时任务,如果存在多个任务,且任务时间过长,会导致执行效果与预期不符。
如果TimerTask
抛出RuntimeException
,Timer
会停止所有任务的运行。
Timer不适用对时效性要求较高的多任务并发作业及对复杂任务的调度。
OpenSymphony
提供的强大的开源任务调度框架
强大的调度功能
灵活的应用方式
分布式和集群能力
设计模式
Bulider模式 、组件模式 、Factory模式 、链式写法
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartzartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartz-jobsartifactId>
<version>2.2.1version>
dependency>
HelloJo.java
import org.quartz.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 实现业务逻辑的接口
* Created by PengHongfu
*/
public class HelloJob implements Job {
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//编写具体的业务逻辑
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println("Hello World! Current time is:" + sf.format(calendar.getTime()));
}
}
HelloScheduler.java
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by PengHongfu
*/
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();
//创建Schedule实例
SchedulerFactory sfat = new StdSchedulerFactory();
Scheduler scheduler = sfat.getScheduler();
scheduler.start();
//打印当前时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current time is:" + sf.format(calendar.getTime()));
scheduler.scheduleJob(jobDetail, trigger);
}
}
Current time is:2018-09-13 11:57:36
Hello World! Current time is:2018-09-13 11:57:36
Hello World! Current time is:2018-09-13 11:57:38
Hello World! Current time is:2018-09-13 11:57:40
Hello World! Current time is:2018-09-13 11:57:42
Hello World! Current time is:2018-09-13 11:57:44
....
Job
实现业务逻辑的任务接口
package org.quartz;
public interface Job {
void execute(JobExecutionContext var1) throws JobExecutionException;
}
获取jobDetail的各种参数
public class HelloScheduler {
public static void main(String args[]) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob class 绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob", "group1").build();
System.out.println("jobDetail's name:"+jobDetail.getKey().getName());
System.out.println("jobDetail's group:"+jobDetail.getKey().getGroup());
System.out.println("jobDetail's jobClass:"+jobDetail.getKey().getClass());
//创建一个Trigger实例,定义该job立即执行,并且每隔两秒重复执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.....
HelloJob1.java
import org.quartz.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 实现业务逻辑的接口
* Created by PengHongfu
*/
public class HelloJob1 implements Job {
private String message;
private Float floatJobValue;
private Double doubleTriggerValue;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//编写具体的业务逻辑
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
//System.out.println(sf.format(calendar.getTime())+":Hello World!");
JobKey key = jobExecutionContext.getJobDetail().getKey();
System.out.println("my Name and group are:"+key.getName()+","+key.getGroup());
TriggerKey triggerKey = jobExecutionContext.getTrigger().getKey();
System.out.println("My trigger name and group are:"+triggerKey.getName()
+";"+triggerKey.getGroup());
JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
JobDataMap tdataMap = jobExecutionContext.getTrigger().getJobDataMap();
String jobMsg = (String) dataMap.get("message");
Float jobFloatValue = (Float) dataMap.get("floatJobValue");
String jobMsg1 = (String) tdataMap.get("message");
Double jobFloatValue2 = (Double) tdataMap.get("doubleTriggerValue");
System.out.println(jobMsg+","+jobFloatValue+","+jobMsg1+","+jobFloatValue2);
//JobDataMap mergedJobDataMapd = jobExecutionContext.getMergedJobDataMap();
System.out.println(message+", "+floatJobValue+" ,"+doubleTriggerValue);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Float getFloatJobValue() {
return floatJobValue;
}
public void setFloatJobValue(Float floatJobValue) {
this.floatJobValue = floatJobValue;
}
public Double getDoubleTriggerValue() {
return doubleTriggerValue;
}
public void setDoubleTriggerValue(Double doubleTriggerValue) {
this.doubleTriggerValue = doubleTriggerValue;
}
}
HelloScheduler1.java
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by PengHongfu
*/
public class HelloScheduler1 {
public static void main(String args[]) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob class 绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob", "group1")
.usingJobData("message","hello myJob1")
.usingJobData("floatJobValue",3.14F).build();
//创建一个Trigger实例,定义该job立即执行,并且每隔两秒重复执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.usingJobData("message","hello myTrigger1")
.usingJobData("doubleTriggerValue",2.0D)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.repeatForever())
.build();
//创建Schedule实例
SchedulerFactory sfat = new StdSchedulerFactory();
Scheduler scheduler = sfat.getScheduler();
scheduler.start();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println("Current time is:"+sf.format(calendar.getTime()));
scheduler.scheduleJob(jobDetail,trigger);
}
}
Current time is:2018-09-13 16:01:21
2018-09-13 16:01:21:Hello World!
my Name and group are:myJob,group1
My trigger name and group are:myTrigger;group1
hello myJob1,3.14,hello myTrigger1,2.0
hello myTrigger1, 3.14 ,2.0
2018-09-13 16:01:23:Hello World!
my Name and group are:myJob,group1
My trigger name and group are:myTrigger;group1
hello myJob1,3.14,hello myTrigger1,2.0
hello myTrigger1, 3.14 ,2.0
Quartz
中的触发器用来告诉调度程序作业什么时候触发。
即Trigger
对象是用来触发执行Job
的。
JobKey
表示job实例的标识,触发器被触发时,该指定的job实例会执行。
StartTime
EndTime
HelloScheduler2.java
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by PengHongfu 2018-09-07 10:04
*/
public class HelloScheduler2 {
public static void main(String args[]) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob class 绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob2.class)
.withIdentity("myJob").build();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
System.out.println("Current time is:" + sf.format(calendar.getTime()));
calendar.add(Calendar.SECOND, 3);
endCalendar.add(Calendar.SECOND, 6);//结束时间6秒之后
//创建一个Trigger实例,定义该job立即执行,并且每隔两秒重复执行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startAt(calendar.getTime())
.endAt(endCalendar.getTime())
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.repeatForever())
.build();
//创建Schedule实例
SchedulerFactory sfat = new StdSchedulerFactory();
Scheduler scheduler = sfat.getScheduler();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
}
}
HelloJob2.java
import org.quartz.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 实现业务逻辑的接口
* Created by PengHongfu 2018-09-07 10:00
*/
public class HelloJob2 implements Job {
private String message;
private Float floatJobValue;
private Double doubleTriggerValue;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//编写具体的业务逻辑
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println("Current time is:"+sf.format(calendar.getTime()));
Trigger currTrigger = jobExecutionContext.getTrigger();
System.out.println("Start time is:"+currTrigger.getStartTime());
System.out.println("End time is:"+currTrigger.getEndTime());
JobKey jobKey = currTrigger.getJobKey();
System.out.println("JobKey info---"+"jobName:"
+jobKey.getName()+" jobGroup"+jobKey.getGroup());
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Float getFloatJobValue() {
return floatJobValue;
}
public void setFloatJobValue(Float floatJobValue) {
this.floatJobValue = floatJobValue;
}
public Double getDoubleTriggerValue() {
return doubleTriggerValue;
}
public void setDoubleTriggerValue(Double doubleTriggerValue) {
this.doubleTriggerValue = doubleTriggerValue;
}
}
Current time is:2018-09-13 16:56:20
Current time is:2018-09-13 16:56:23
Start time is:Thu Sep 13 16:56:23 CST 2018
End time is:Thu Sep 13 16:56:26 CST 2018
JobKey info---jobName:myJob jobGroupDEFAULT
Current time is:2018-09-13 16:56:25
Start time is:Thu Sep 13 16:56:23 CST 2018
End time is:Thu Sep 13 16:56:26 CST 2018
JobKey info---jobName:myJob jobGroupDEFAULT
import org.quartz.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 实现业务逻辑的接口
* Created by PengHongfu
*/
public class HelloJob implements Job {
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//编写具体的业务逻辑
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println("Hello World! Current time is:" + sf.format(calendar.getTime()));
}
}
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by PengHongfu 2018-09-07 10:04
*/
public class HelloScheduler {
public static void main(String args[]) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob class 绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob").build();
//距离当前时间4s后执行一次
Date date = new Date();
date.setTime(date.getTime()+4000L);
Date endDate = new Date();
endDate.setTime(endDate.getTime()+6000L);
SimpleTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startAt(date)
.endAt(endDate)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.withRepeatCount(3))
.build();
//创建Schedule实例
SchedulerFactory sfat = new StdSchedulerFactory();
Scheduler scheduler = sfat.getScheduler();
scheduler.start();
//打印当前时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current time is:" + sf.format(calendar.getTime()));
scheduler.scheduleJob(jobDetail, trigger);
}
}
在线工具地址:http://cron.qqe2.com
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by PengHongfu
*/
public class HelloScheduler {
public static void main(String args[]) throws SchedulerException {
//创建一个JobDetail实例,将该实例与HelloJob class 绑定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob").build();
//每秒执行一次任务
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("* * * * * ? *"))
.build();
/**
* 2017年内每天10点15分触发一次
* 0 15 10 ? * * 2017
* 每天的14点整至14点59分55秒,以及18点整至18点59分55秒,每5秒钟触发一次
* 0/5 * 14,18 * * ?
* 每月周一至周五的10点15分触发一次
* * 15 10 * * MON-FRI ?
* 每月最后一天的10点15分触发一次
* * 15 10 L * ? ?
* 每月第三周五的10点15分触发一次
* * 15 10 * * FRI#3 ?
*/
//创建Schedule实例
SchedulerFactory sfat = new StdSchedulerFactory();
Scheduler scheduler = sfat.getScheduler();
scheduler.start();
//打印当前时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Current time is:" + sf.format(calendar.getTime()));
scheduler.scheduleJob(jobDetail, trigger);
}
}
scheduler.scheduleJob(jobDetail, trigger);
//每个Job都会有一个新的线程去运行,每个Job在他的当前线程都会sleep一次。
//schedule执行两秒后挂起
Thread.sleep(2000L);
scheduler.standby();
//shcedule挂起三秒后继续执行
Thread.sleep(3000L);
scheduler.start();
//shutdown(true)表示等待所以正在执行的job执行完毕之后,关闭shcedule
//shutdown(false)即直接关闭schedule
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore