quartz2小实例

任务类

package org.gof.test;

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

public class HelloJob implements Job {

    private String hello;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {

        System.out.println(hello);
    }
}

调度器

package org.gof.test;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

public class MySchedule {

    private Scheduler scheduler;

    public void start(){
        try {
            scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void addTask(JobDetail job,Trigger trigger){
        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


}

测试类

package org.gof.test;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class Test {

    public static void main(String[] args)throws Exception {

        Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("triggerName1", "group1")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();

        Trigger trigger2 = TriggerBuilder
                .newTrigger()
                .withIdentity("triggerName2", "group1")
                .withSchedule(
                    CronScheduleBuilder.cronSchedule("0/2 * * * * ?"))
                .build();


        JobDetail job1 = JobBuilder.newJob(HelloJob.class).withIdentity("dummyJobName1", "group1").build();
        job1.getJobDataMap().put("hello", "hello World");


        JobDetail job2 = JobBuilder.newJob(HelloJob.class).withIdentity("dummyJobName2", "group1").build();
        job2.getJobDataMap().put("hello", "hello quartz");



        MySchedule ms = new MySchedule();
        ms.start();

        ms.addTask(job1, trigger1);
        ms.addTask(job2, trigger2);
    }

}

输出结果

hello World
hello quartz
hello World
hello quartz
hello World
hello quartz
hello World
hello quartz
hello World
hello quartz
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值