报名立减200元。暑假直降6888。
邀请链接:http://www.jnshu.com/login/1/20535344
邀请码:20535344
添加quartz到Java应用中很容易,只需要学习一些概念就可以开始。
首先需要 Quartz Core Library,quartz-version.jar。Quartz只需要很少是依赖,通常至少需要sl4f-api.jar。如果需要将schedualing data存进数据库,则需要c3p0 library。
You may also want the quartz-jobs jar file on your classpath - if you want to use any of the jobs "built into" quartz.
You can download the full distribution (with examples, source, dependencies, doc, etc.).
1.添加Quartz到应用(maven)
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
2.使用quartz
2.1启动一个Scheduler
Schedulers 是由factories创建的。Schedulers可以立刻被用来调度jobs,但是只有在调用了.start()方法后,才开始执行单元。
//从工厂获取Scheduler实例
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//启动它
sheduler.start();
2.2 code with the Quartz Fluent Scheduling API
The Quartz API 被设计成向DSL(domain-specific language)一样流畅。如果采用静态地方法来引入API components 可以很轻松。(import 也可以static?)
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
完成上面操作后就可以实现Jobs,必须有一个.execute();方法。
public class MyJob implements org.quartz.Job {
public MyJob() {
}
public void execute(JobExecutionContext context) throws JobExecutionException {
System.err.println("Hello World! MyJob is executing.");
}
}
之后可以用triggers来调度(schedule)这些jobs。trigger 是用来定义job该被哪个时间执行。
// define the job and tie it to our MyJob class(定义job并绑定到MyJob类)
JobDetail job = newJob(MyJob.class)
.withIdentity("job1", "group1")
.build();
// Trigger the job to run now, and then repeat every 40 seconds(job现在启动,然后设置为40秒重复一次)
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger(告诉quarts用我们创建的trigger来调度job)
scheduler.scheduleJob(job, trigger);