package test;
import java.text.ParseException;
import java.util.Date;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
public class TestJob implements Job{
private static intcnt = 0;
@Override
public voidexecute(JobExecutionContext context) throws JobExecutionException {
System.out.println("TestJob" + (++cnt) + " Run! " +new Date());
Scheduler scheduler=context.getScheduler();//獲取執(zhí)行的Scheduler
try {//執(zhí)行3次之后關(guān)閉
if(!scheduler.isShutdown()&&cnt==3)//判斷是否在執(zhí)行
scheduler.shutdown();
} catch(SchedulerException e) {
e.printStackTrace();
}
}
public static voidmain(String [] args) throws SchedulerException, ParseException{
SchedulerFactoryschedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
sched.start();//調(diào)度器啟動
// 參數(shù):任務(wù)名,任務(wù)組,任務(wù)執(zhí)行類 ,任務(wù)執(zhí)行類決定執(zhí)行哪個execute方法
JobDetail jobDetail = new JobDetail("TestJob",
"TestJobGroup", TestJob.class);
//觸發(fā)器
CronTrigger trigger = newCronTrigger("TestJob","TestJobGroup");// 觸發(fā)器名,觸發(fā)器組
//觸發(fā)事件設(shè)定
trigger.setCronExpression("0/3 * * * * ? ");//每3s執(zhí)行一次
//將任務(wù)和觸發(fā)器加入調(diào)度器,會執(zhí)行execute方法
sched.scheduleJob(jobDetail, trigger);
}
}
網(wǎng)上找教程,大致實現(xiàn)了功能,觸發(fā)器的時間設(shè)置詳解鏈接為:
http://www.open-open.com/lib/view/open1392211610489.html
大致理解:格式 [秒] [分] [小時] [日] [月] [周] [年]
0/n在 分 位置表示每幾分鐘執(zhí)行一次
0/n在 時 位置表示每幾小時執(zhí)行一次
其余相同,*通配符,?表示不確定