Java · 成长之路Java学习笔记程序员

Quartz入门(二) --多任务

2017-06-15  本文已影响98人  是夏莞也是CiCi

Quartz入门(二) --多任务

通过一里面的例子可以看出Quartz执行的一般过程。

这个例子是实现了多任务,即将多个任务注册到Scheduler。其中job3可以等间隔重复执行

package SecondDemo;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Calendar;

/**
 * Created by CiCi on 2017/5/2.
 */
public class MyJob2 implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // @NOTICE JobExecutionContext 是任务执行的上下文,可以拿到任务的Key
        String jobName = jobExecutionContext.getJobDetail().getKey().getName();
        System.out.println("任务Key:" + jobName + " 正在执行,执行时间: " + Calendar.getInstance().getTime());
    }
}
package SecondDemo;


import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
 * Created by CiCi on 2017/5/2.
 */
public class QuartzMultiJobTest {
    public static void main(String[] args) throws Throwable{
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();

        //任务的开始时间,nextGivenSecondDate方法表示:当前时间之后,每当秒数是13的倍数都是触发时间,当然只触发一次
        // 比如:00:00:12秒开始主线程,则13秒就会触发任务,如果00:00:14秒开始主线程,则在26秒触发任务
        Date runTime = DateBuilder.nextGivenSecondDate(null,13);

        JobDetail job = JobBuilder.newJob(MyJob2.class).withIdentity("job1","group1").build();
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startAt(runTime).build();
        scheduler.scheduleJob(job,trigger);

        //将同一个Job实现作为另一个任务注册到Scheduler,注意名字要区分
        job = JobBuilder.newJob(MyJob2.class).withIdentity("job2","group1").build();
        trigger = TriggerBuilder.newTrigger().withIdentity("trigger2","group1").startAt(runTime).build();
        scheduler.scheduleJob(job,trigger);

        //job3表示重复执行,第一次执行完后,每隔3秒执行一次,withRepeatCount参数不包括第一次执行那次,即job3总共执行了6次
        job = JobBuilder.newJob(MyJob2.class).withIdentity("job3","group1").build();
        trigger = TriggerBuilder.newTrigger().withIdentity("trigger3","group1").withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(5).withIntervalInSeconds(3)).startAt(runTime).build();
        scheduler.scheduleJob(job,trigger);

        scheduler.start();

        try {
            Thread.sleep(20L * 1000L);
        }catch (Exception e) {
            e.printStackTrace();
        }

        scheduler.shutdown(true);

    }
}

That's all. Thank U~

上一篇下一篇

猜你喜欢

热点阅读