浅谈Trigger
什么是Trigger?
Quartz中的觸發器用來告訴調度程序作業什么時候觸發。即Trigger對象是用來觸發Job的
JobKey表示Job實例的標識,觸發器被觸發時,該指定的Job實例會執行。
StartTime 表示觸發器的時間表首次被觸發的時間。它的值的類型是Java.util.Date
EndTime 指定觸發器的不再被觸發的時間。它的值的類型是Java.util.Date
具體案例
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 {
//打印當前的執行時間
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(date);
System.out.println("Current Time : "+currentTime);
//獲取當前時間3秒后的時間
date.setTime(date.getTime()+3000);
//獲取距離當前時間6秒后的時間
Date endDate = new Date();
endDate.setTime(endDate.getTime()+6000);
//創建一個JobDetail實例,將該實例與HelloJob class綁定
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
.withIdentity("myJob", "group1")
.build();
//創建一個Trigger實例,定義該Job立即執行,并且每隔2秒鐘重復執行一次,直到永遠
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startAt(date)
.endAt(endDate)
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
.build();
//創建Scheduler實例
SchedulerFactory sfact = new StdSchedulerFactory();
Scheduler scheduler = sfact.getScheduler();
scheduler.start();
scheduler.scheduleJob(jobDetail, trigger);
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Trigger;
public class HelloJob implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {
//打印當前的執行時間
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(date);
System.out.println("Current Exec Time : "+currentTime);
//編寫具體的業務邏輯
Trigger currentTrigger = context.getTrigger();
System.out.println("Start Time is:"+sdf.format(currentTrigger.getStartTime()));
System.out.println("End Time is:"+sdf.format(currentTrigger.getEndTime()));
JobKey jobKey = currentTrigger.getJobKey();
System.out.println("JobKey info --" +jobKey.getName()+": "+jobKey.getGroup()+": "+jobKey.getClass());
}
}
總結
- 上一篇: 官降小 5 万,大众 ID.4 CROZ
- 下一篇: WAMP设置