2. 在web.xml中添加quartz的监听器org.quartz-scheduler quartz 2.2.1 org.quartz-scheduler quartz-jobs 2.2.1
3. 添加quartz.properties配置文件org.quartz.ee.servlet.QuartzInitializerListener
# Configure Main Scheduler Propertiesorg.quartz.scheduler.instanceName: dufy_testorg.quartz.scheduler.instanceId = AUTOorg.quartz.scheduler.rmi.export: falseorg.quartz.scheduler.rmi.proxy: falseorg.quartz.scheduler.wrapJobExecutionInUserTransaction: false# Configure ThreadPoolorg.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPoolorg.quartz.threadPool.threadCount: 2org.quartz.threadPool.threadPriority: 5org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: trueorg.quartz.jobStore.misfireThreshold: 60000# Configure JobStore 持久化配置#org.quartz.jobStore.class: org.quartz.simpl.RAMJobStoreorg.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTXorg.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegateorg.quartz.jobStore.useProperties:true# 是否集群org.quartz.jobStore.isClustered = false # 表前缀org.quartz.jobStore.tablePrefix:qrtz_#org.quartz.jobStore.dataSource:qzDS# 下面是数据库的配置,交给Spring管理了#org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver#org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz_test#org.quartz.dataSource.qzDS.user:root#org.quartz.dataSource.qzDS.password:123#org.quartz.dataSource.qzDS.maxConnection:10
4. 添加Spring配置:applicationContext-quartz.xml
5. 将��ʳ,����Quartz自带的表导入Mysql
6. 自己建立管理定时任务的表,我简单写了几个必须的属性create table qrtz_job_details(sched_name varchar(120) not null,job_name varchar(80) not null,job_group varchar(80) not null,description varchar(120),job_class_name varchar(128) not null,is_durable integer not null,is_nonconcurrent integer not null,is_update_data integer not null,requests_recovery integer not null,job_data blob(2000),primary key (sched_name,job_name,job_group));create table qrtz_triggers(sched_name varchar(120) not null,trigger_name varchar(80) not null,trigger_group varchar(80) not null,job_name varchar(80) not null,job_group varchar(80) not null,description varchar(120),next_fire_time bigint,prev_fire_time bigint,priority integer,trigger_state varchar(16) not null,trigger_type varchar(8) not null,start_time bigint not null,end_time bigint,calendar_name varchar(80),misfire_instr smallint,job_data blob(2000),primary key (sched_name,trigger_name,trigger_group),foreign key (sched_name,job_name,job_group) references qrtz_job_details(sched_name,job_name,job_group));create table qrtz_simple_triggers(sched_name varchar(120) not null,trigger_name varchar(80) not null,trigger_group varchar(80) not null,repeat_count bigint not null,repeat_interval bigint not null,times_triggered bigint not null,primary key (sched_name,trigger_name,trigger_group),foreign key (sched_name,trigger_name,trigger_group) references qrtz_triggers(sched_name,trigger_name,trigger_group));create table qrtz_cron_triggers(sched_name varchar(120) not null,trigger_name varchar(80) not null,trigger_group varchar(80) not null,cron_expression varchar(120) not null,time_zone_id varchar(80),primary key (sched_name,trigger_name,trigger_group),foreign key (sched_name,trigger_name,trigger_group) references qrtz_triggers(sched_name,trigger_name,trigger_group));CREATE TABLE qrtz_simprop_triggers( sched_name varchar(120) not null, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, STR_PROP_1 VARCHAR(512) NULL, STR_PROP_2 VARCHAR(512) NULL, STR_PROP_3 VARCHAR(512) NULL, INT_PROP_1 INT NULL, INT_PROP_2 INT NULL, LONG_PROP_1 BIGINT NULL, LONG_PROP_2 BIGINT NULL, DEC_PROP_1 NUMERIC(13,4) NULL, DEC_PROP_2 NUMERIC(13,4) NULL, BOOL_PROP_1 VARCHAR(1) NULL, BOOL_PROP_2 VARCHAR(1) NULL, PRIMARY KEY (sched_name,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (sched_name,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(sched_name,TRIGGER_NAME,TRIGGER_GROUP));create table qrtz_blob_triggers(sched_name varchar(120) not null,trigger_name varchar(80) not null,trigger_group varchar(80) not null,blob_data blob(2000),primary key (sched_name,trigger_name,trigger_group),foreign key (sched_name,trigger_name,trigger_group) references qrtz_triggers(sched_name,trigger_name,trigger_group));create table qrtz_calendars(sched_name varchar(120) not null,calendar_name varchar(80) not null,calendar blob(2000) not null,primary key (calendar_name));create table qrtz_fired_triggers(sched_name varchar(120) not null,entry_id varchar(95) not null,trigger_name varchar(80) not null,trigger_group varchar(80) not null,instance_name varchar(80) not null,fired_time bigint not null,sched_time bigint not null,priority integer not null,state varchar(16) not null,job_name varchar(80),job_group varchar(80),is_nonconcurrent integer,requests_recovery integer,primary key (sched_name,entry_id));create table qrtz_paused_trigger_grps(sched_name varchar(120) not null,trigger_group varchar(80) not null,primary key (sched_name,trigger_group));create table qrtz_scheduler_state(sched_name varchar(120) not null,instance_name varchar(80) not null,last_checkin_time bigint not null,checkin_interval bigint not null,primary key (sched_name,instance_name));create table qrtz_locks(sched_name varchar(120) not null,lock_name varchar(40) not null,primary key (sched_name,lock_name));
7. 准备俩简单的Jsp页面用于添加定时任务和定时任务列表展示public class QuartzTask {/* * 这个类用于展示定时的任务,同时作用于定时任务的恢复、删除、中止; **/private Long jobId;private String jobClass; //任务类的全限定类名private String jobGroup; //任务组名private String jobName; //任务名private String triggerName; //任务触发器名private String triggerGroupName; //任务触发器组名private String cronExpr; //时间表达式private Integer jobStatus; //任务状态private String startTime; //任务开始时间}
大致效果如下:
二、简单代码实现1.写个任务类,本想做个功能,失败了,就简单控制台输出了2. Controller层:QuartzControllerpublic class MyJob implements Job{private static final Logger log = LoggerFactory.getLogger(MyJob.class);@Overridepublic void execute(JobExecutionContext arg0) throws JobExecutionException {log.info("MyJob is start .................."); log.info("Hello quzrtz "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));log.info("MyJob is end .....................");}}
3. Service层:QuartzTaskServiceImpl@Controller@RequestMapping("user/quartz")public class QuartzController {@Autowired private QuartzTaskService quartzTaskService;/** * 添加定时任务 * */@RequestMapping(value = "add",method = RequestMethod.POST)public ModelAndView addQtz(QuartzTask qt){try {//1.成功启动定时任务this.quartzTaskService.addQtz(qt);//2.封装QuartzTask,执行保存this.quartzTaskService.saveAddQtz(qt);return new ModelAndView("success");} catch (Exception e) {e.printStackTrace();}return new ModelAndView("error");}/** * 定时任务列表 * */@RequestMapping(value = "list",method = RequestMethod.GET)public ModelAndView listQtz(){try {//1.查询所有定时任务Listlist = this.quartzTaskService.listQtz();ModelAndView mv = new ModelAndView();mv.addObject("qtzList",list);mv.setViewName("quartz-list");return mv;} catch (Exception e) {e.printStackTrace();}return new ModelAndView("error");}/** * 删除定时任务 * */@RequestMapping(value = "delete",method = RequestMethod.GET)public ModelAndView deleteQtz(QuartzTask qt){try {// 执行删除this.quartzTaskService.deleteQtz(qt);// 根据id删除定时任务列表数据this.quartzTaskService.deleteQtzTask(qt.getJobId());return new ModelAndView("success");} catch (Exception e) {e.printStackTrace();}return new ModelAndView("error");}/** * 中止定时任务 * */@RequestMapping(value = "pause",method = RequestMethod.GET)public ModelAndView pauseQtz(QuartzTask qt){try {// 执行中止this.quartzTaskService.pauseQtz(qt);return new ModelAndView("success");} catch (Exception e) {e.printStackTrace();}return new ModelAndView("error");}/** * 恢复定时任务 * */@RequestMapping(value = "resume",method = RequestMethod.GET)public ModelAndView resumeQtz(QuartzTask qt){try {// 执行中止this.quartzTaskService.resumeQtz(qt);return new ModelAndView("success");} catch (Exception e) {e.printStackTrace();}return new ModelAndView("error");}}
4. 与数据库交互的QuartzTask.xml文件@Servicepublic class QuartzTaskServiceImpl implements QuartzTaskService {@Autowiredprivate QuartzDao quartzDao;@Autowiredprivate Scheduler scheduler;@Overridepublic void addQtz(QuartzTask qt) {try {// 1.创建一个JobDetail实例,指定QuartzString cla = qt.getJobClass();Class clazz = Class.forName(cla);JobDetail jobDetail = JobBuilder.newJob(clazz) // 任务执行类.withIdentity(qt.getJobName(), qt.getJobGroup())// 任务名,任务组.build();CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(qt.getCronExpr());// 2.创建Trigger(触发器)Trigger trigger = TriggerBuilder.newTrigger().withIdentity(qt.getTriggerName(), qt.getTriggerGroupName()).startNow().withSchedule(builder).build();// 3.告诉调度器使用该触发器来安排作业scheduler.scheduleJob(jobDetail, trigger);// 4.启动if (!scheduler.isShutdown()) { scheduler.start();}} catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic void saveAddQtz(QuartzTask qt) {qt.setJobId(1l);qt.setJobStatus(1);qt.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));this.quartzDao.saveAddQtz(qt);}@Overridepublic ListlistQtz() {return quartzDao.listQtz();}@Overridepublic void deleteQtz(QuartzTask qt) {try {// 停止触发器scheduler.pauseTrigger(TriggerKey.triggerKey(qt.getTriggerName(), qt.getTriggerGroupName()));// 移除触发器scheduler.unscheduleJob(TriggerKey.triggerKey(qt.getTriggerName(), qt.getTriggerGroupName()));// 删除任务scheduler.deleteJob(JobKey.jobKey(qt.getJobName(), qt.getJobGroup()));} catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic void deleteQtzTask(Long jobId) {this.quartzDao.deleteQtzTask(jobId);}@Overridepublic void pauseQtz(QuartzTask qt) {try {scheduler.pauseJob(JobKey.jobKey(qt.getJobName(), qt.getJobGroup()));} catch (SchedulerException e) {e.printStackTrace();}}@Overridepublic void resumeQtz(QuartzTask qt) {try {scheduler.resumeJob(JobKey.jobKey(qt.getJobName(), qt.getJobGroup()));} catch (SchedulerException e) {e.printStackTrace();}}}
INSERT INTO quartz(job_id,job_class,job_group,job_name,trigger_name,trigger_groupName,cron_expr,job_status,start_time)VALUES(#{jobId},#{jobClass},#{jobGroup},#{jobName},#{triggerName},#{triggerGroupName},#{cronExpr},#{jobStatus},#{startTime}); select * from quartz;DELETE from quartz where job_id = #{jobId};
我这里只做了简单实现,还有很多地方不懂,继续努力。