1.背景
在企业应用中,经常有一些定时任务需要执行:
1)生成月报,季报和年报,这时候可以使用数据库的作业运行存储过程来实现;
2)定期查询哪些待审核单据即将过期,并给待审核人发送提醒邮件,可以使用powershell脚本来做一个发送邮件的功能,在数据库的作业中来调用。
...
诸如此类的很多需求,通常会做一个windows service 运行在应用服务器上,定时执行去执行一些任务。这时候如果任务比较多,还需要个性化定制触发器,业务逻辑可能就比较复杂了,协调各个任务之间的关系就不那么简单了。为了解决这个问题,Quartz就诞生了,这是一个企业级的任务调度框架。下面就看看Quartz的一些情况。
2.概要
1)官网:http://www.quartz-scheduler.org/
从下载到文档到Demo,一应俱全,官网是最好的学习资源(英文不太好的同学请自行脑补...)
2.Demo
1)新建java工程
导入如下jar包...
log4j.xml可以直接用example里面的配置
2)JobTest.java
package com.wicresoft.demo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class JobTest implements Job{
//Instances of Job must have a public no-argument constructor
public JobTest(){
}
public void execute(JobExecutionContext arg0) throws JobExecutionException {
//print the job instance,all instance are not the same
System.out.println("My task is to call current Job:" + this + " refresh screen!!!");
}
}
3)QuartzTest.java
package com.wicresoft.demo;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
//import org.quartz.JobBuilder.*;
//import org.quartz.TriggerBuilder.*;
//import org.quartz.Trigger;
//import org.quartz.SimpleScheduleBuilder.*;
public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// define the job and tie it to our HelloJob class
JobDetail job = JobBuilder.newJob(JobTest.class)
.withIdentity("job1", "group1").build();
// Trigger the job to run now, and then repeat every 2 seconds
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2).repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
// and start it off
scheduler.start();
// mail thread sleep 2 seconds
//System.out.println(Thread.currentThread().getName());
Thread.sleep(30 * 1000);
scheduler.shutdown();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
PS:
1.Quartz 已经有了.NET版本,使用起来基本与java一致,这里推荐lee576的一篇关于.net Quartz的介绍:
http://blog.youkuaiyun.com/lee576/article/details/46048927