1. 程式人生 > >Quartz四 按固定間隔一直執行

Quartz四 按固定間隔一直執行

package com.converter.test;


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


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;


public class SimpleJob implements Job {


@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
TriggerKey key=arg0.getTrigger().getKey();
System.out.println(key+" 執行時間為:"+sf.format(new Date()));
}


}

package com.converter.test;


import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.DateBuilder.futureDate;


import java.util.Date;


import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;


public class Quartz_test4 {


public static void main(String[] args) throws SchedulerException {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler=sf.getScheduler();

Date runTime = evenMinuteDate(new Date());

JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1").build();
//設定5分鐘後執行一次
//SimpleTrigger simpleTrigger = (SimpleTrigger) newTrigger().withIdentity("trigger2", "group2")
//.startAt(futureDate(5,IntervalUnit.MINUTE)).build();

//每40秒執行一次
SimpleTrigger simpleTrigger=(SimpleTrigger) newTrigger().withIdentity("trigger2","group2").startAt(runTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(4).repeatForever()).build();

Date ft=scheduler.scheduleJob(job, simpleTrigger);
  System.out.println(job.getKey() + " will run at: " + ft + " and repeat: " + simpleTrigger.getRepeatCount() + " times, every "
            + simpleTrigger.getRepeatInterval() / 1000 + " seconds");



scheduler.start();



}


}