Java 定时框架Quartz使用

本文档详细介绍了如何使用 Quartz Scheduler 进行定时任务管理,包括启动和停止调度器、定义带输入数据的作业、调度和取消作业、存储作业、更新作业和触发器,以及创建和注册作业监听器和触发器监听器。Quartz 是一个强大且灵活的开源作业调度框架,用于在 Java 应用中安排任务。
摘要由CSDN通过智能技术生成

http://www.quartz-scheduler.org/documentation/quartz-2.3.0/cookbook 

1. 将scheduler放在闲置状态:

// already called start() previously
scheduler.standby(); // now the scheduler will not fire triggers / execute jobs
scheduler.start(); // now the scheduler will fire triggers and execute jobs

2. 关闭scheduler:

// waiting for executing jobs to Finish
scheduler.shutdown(true);

// do not waiting for executing jobs to Finish
// shutdown() returns immediately, but executing job continue running to complele
scheduler.shutdown();
scheduler.shutdown(false);

3. defining a job (with input data)

public class PrintPropsJob implements Job {

	public PrintPropsJob() {
		// Instances of Job must have a public no-argument constructor.
	}

	public void execute(JobExecutionContext context) 
			throws JobExecutionException {

		JobDataMap data = context.getMergedJobDataMap();  // 输入数据
		System.out.println("someProp = " + data.getString("someProp"));
	}

}
// Define job instance
JobDetail job1 = newJob(MyJobClass.class)
    .withIdentity("job1", "group1")
    .usingJobData("someProp", "someValue")
    .build();

Also note that if your Job class contains setter methods that match your JobDataMap keys, and you use the default JobFactory implementation, then Quartz will automatically call the setter method with the JobDataMap value, and there is no need to have code in the Job’s execute method that retrieves the value from the JobDataMap.

来源: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/cookbook/DefineJobWithData.html

4. scheduling a job

// define job instance 
JobDetail job1 = newJob(ColorJob.class)
    .withIdentity("job1", "gourp1")
    .build();

// Define a Trigger that will fire "now", and not repeat
Trigger trigger = newTrigger()
    .withIdenttiy("tiggger1", "group1")
    .startNow()
    .build();
// schedule the job with the trigger
sched.scheduleJob(job, trigger);

5. unscheduling a job(取消定时任务)

// 1. Unscheduling a particular Trigger of Job
// Unschedule a particular trigger from the job (a job may have more than one trigger)
scheduler.unscheduleJob(triggerKey("trigger1", "group1"));

// 2. Deleting a Job and Unscheduling All of its triggers
scheduler.deleteJob(jobKey("job1", "group1"));

6. Storign a job for later use(存储一个job供随后使用)

// define a durable(持久性的) job instance (durable jobs can exist without triggers)
// 持久性的任务可以在没有配置triggers的情况下存在
JobDetail job1 = newJob(MyJobClass.class)
    .withIdentity("job1","group1")
    .storeDuably()
    .build();

// Add the job to the schedulers store, 将job添加到scheduler的仓库中
sched.addJob(job, false);  // 第二个参数false表示,如果存在相同identity的job不进行替换

7. Scheduling an already stored job:调度一个已经存储的job

// Define a Trigger that will fire "now" and associate it with the existing job
Trigger trigger = newTrigger()
    .withIdentity("trigger1", "group1")
    .startNow()
    .forJob(jobKey("job1", "group1"))
    .build();

// Schedule the trigger
sched.scheduleJob(trigger)

8. Update an existing job:

// Add the new job to the scheduler, instructing it to "replace" the existing job with the given name and group (if any)
JobDetail job1 = newJob(MyJobClass.class)
    .withIdentity("job1", "group1")
    .build();

// store, and set overwrite flag to "true"
// 保存,并且设置重写标志为 true
scheduler.addJob(job1, true);

9. Update a trigger:

Replace a trigger: 替换一个trigger

// Define a new Trigger 创建一个新的trigger
Trigger trigger = newTrigger()
    .withIdentity("newTrigger", "group1")
    .startNow()
    .build();

// tell the scheduler to remove the old trigger with the given key, and put the new one in its place
// 告诉调度器移除旧的触发器(根据triggerKey),并且将新的放在他的位置上
sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger);

Update an existsing trigger:更新一个存在的trigger

// retrive the trigger 获取已经存在的trigger 
Trigger oldTrigger = sched.getTrigger(triggerKey("oldTrigger", "group1"));

// obtain a builder that would produce the trigger
TriggerBuilder tb = oldTrigger.getTriggerBuilder();

// update the schedule associated with the builder , and build the new trigger
// (other builder methors could be called, to change the trigger in any desired way)
Trigger newTrigger = tb.withSchedule(simpleSchedule)
    .withIntervalInSeconds(10)
    .withRepeatCount(10)
    .build();

sched.resheduleJob(oldTrigger.getKey(), newTrigger);

10. Listing jobs in the Scheduler: 列出调度器中所有job

// enumerate each trigger group
for(String group : sched.getTriggerGroupNames()) {
	// enumerate each trigger in group
    for(TriggerKey triggerKey : sched.getTriggerKeys(groupEquals(group))) {
    	System.out.println("Found trigger identified by: " + triggerKey);
    }
}

12. Finding triggers of a job: 获取一个job的所有触发器

List<Trigger> jobTriggers = sched.getTriggersOfJob(jobKey("jobName", "jobGroup"));

13. creating a JobListener: 创建一个任务监听器

package foo;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

public class MyJobListener implements JobListener {
	private String name;
    public MyJobListener(String name) { this.name = name; }
    public String getName() { return name; }
    public void jobToBeExecuted(JobExecutionContext context) { // do something 
    }
    public void jobWasExecuted(JobExecutionContext context, JobExcutionException jobException) { // do... 
    } 
    public void jobExecutionVetoed(JobExecutionContext context) { // do something
    }  // scheduler在JobDetail即将被执行,但又被TriggerListener否决时调用了这个方法
}
package foo;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.listeners.JobListenerSupport;

public class MyOtherJobListener extends JobListenerSupport {  // 这样不用全部都重写
    private String name;
    public MyOtherJobListener(String name) { this.name = name; }
	public String getName() { return name; }
	@override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { // do something 
    }
}
// 1. registering a jobListener with the scheduler to listen to all jobs
scheduler.getListenerManger().addJobListener(myJobListener, allJobs());

// 2. registering a jobListener with the scheduler to listen a specific job
scheduler.getListenerManger().addJobListener(myJobListener, jobKeyEquals(jobKey("myJobName", "myJobGroup")));

// 3. registering a jobListener with the scheduler to listen to all jobs in a group
scheduler.getListenerManager().addJobListener(myJobListener, jobGroupEquals("myJobGroup"));

14. Creating a TriggerListener: 创建一个触发器监听器

package foo;

import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.quartz.Trigger.CompletedExecutionInstruction;

public class MyTriggerListener implements TriggerListener {
	private String name;
    public MyTriggerListener(String name) { this.name = name; }
    public String getName() { return name; }
    public void triggerComplete(Trigger trigger, JobExecutionContext context, CompletedExecutionInstruction triggerInstructionCode) { }  // 当trigger已经触发且关联的JobDetai执行完成,该函数被执行。
    public void triggerFired(Trigger trigger, JobExecutionContext context) {} // 当一个触发器已经触发且job将要执行时执行该函数
    public void triggerMisFired(Trigger trigger) {}  // 当trigger错过触发(misfire)时执行该函数
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) { return false;} // 在triggerFired之后执行,当一个trigger被触发且其关联的JobDetail将要执行,如果返回true,该job将被 veto(否决),为false则继续执行job
}
package foo;

import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.listeners.TriggerListenerSupport;

public class MyOtherTriggerListener extends TriggerListenerSupport {
 	private String name;
    public MyOtherTriggerListener(String name) { this.name = name; }
    public String getName() { return name; }
    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) { } 
}
// 1. registering a TriggerListener with the scheduler to listen to all triggers
scheduler.getListenerManager().addTriggerListener(myTriggerListener, allTriggers());
// 2. registering a TriggerListener with the scheduler to listen to a specific trigger
scheduler.getListenerManager().addTriggerListener(myTriggerLisener, triggerKeyEquals(triggerKey("myTriggerName", "myTriggerGroup")));
// 3. registering a TriggerListener with the scheduler to listen to all triggers in a group
scheduler.getListenerManager().addTriggerListener(myTriggerListener, triggerGroupEquals("myTriggerGroup"));

15. Creating a SchedulerListener

package foo;

import org.quartz.Trigger;
import org.quartz.listeners.SchedulerListenerSupport;

public class MyOtherSchedulerListener extends SchedulerListenerSupport {
 	@Override
    public void schedulerStarted() {}
    
    @Override
    public void shedulerShuttdown() {}
    
    @Override
    public void jobScheduled(Trigger trigger) {}
    
    //...
}
scheduler.getListenerManager().addSchedulerListener(mySchedListener);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanqiliang630

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值