调度类
package com.huating.jfp.schedule;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
public class MySchedule {
/**
* 简单的线程调度
*
* */
@SuppressWarnings("unchecked")
public void startSchedual() {
try {
Scheduler scheduler = ScheduleManager.getInstance().getSchedule();
/*--------定义任务-----------*/
//本来以为jobdetail类似thread类,但开起来不是,因为把线程(job)加入进来之后,不能自己启动,必须要借助第三方调度
JobDetail jobDetailImpl = new JobDetail("job-synchdata", scheduler.DEFAULT_GROUP, ExcTask.class);
/*--------定义触发器-----------*/
CronTrigger cronTrigger = new CronTrigger("trigger-synchdata", scheduler.DEFAULT_GROUP);
//表达式 每天凌晨2点执行一次("0 0 2 * * ?") 每分钟执行一次(0 * */1 * * ?)
CronExpression cronExpression = new CronExpression("0 * */1 * * ?");
//表达式添加进调度规则中
cronTrigger.setCronExpression(cronExpression);
scheduler.scheduleJob(jobDetailImpl, cronTrigger);
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new MySchedule().startSchedual();
}
}
实际执行的类
package com.huating.jfp.schedule;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class ExcTask implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
System.out.println("我来执行方法了" + sdf.format(new Date()) );
}
}
demo下载地址:
http://download.csdn.net/detail/heqinghua217/9683551
辅助类:
package com.huating.jfp.schedule;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
public class ScheduleManager {
//懒汉式单例类.在第一次调用的时候实例化
//私有的默认构造子
private ScheduleManager() {}
private static ScheduleManager scheduleManager = null;
private static Scheduler scheduler = null;
//静态工厂方法 synchronized这里我去掉了,因为我已经做了控制,永远不会存在第一次并发情况
public static synchronized ScheduleManager getInstance() {
try {
if (scheduleManager == null) {
scheduleManager = new ScheduleManager();
//任务调度器
StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
}
} catch (SchedulerException e) {
e.printStackTrace();
}
return scheduleManager;
}
public Scheduler getSchedule(){
return scheduler;
}
}