首頁  >  文章  >  Java  >  如何在Java中使用Quartz實作定時任務?

如何在Java中使用Quartz實作定時任務?

王林
王林轉載
2023-05-08 10:46:171527瀏覽

Scheduler 每次執行,都會根據JobDetail建立一個新的Job實例,這樣就可以規避並發存取的問題(jobDetail的實例也是新的)

Quzrtz 定時任務預設都是並發執行,不會等待上一次任務執行完畢,只要間隔時間到就會執行,如果定時任務執行太長,會長時間佔用資源,導致其它任務堵塞

#@DisallowConcurrentExecution: job類上,禁止並發地執行同一個job定義(JobDetail定義的)的多個實例。

如何在Java中使用Quartz實作定時任務?

  • scheduler:可以理解為定時任務的工作容器或是工作場所,所有定時任務都是放在裡面工作,可以開啟和停止。

  • trigger:可以理解為是定時任務任務的工作規則配置,例如說,沒幾分鐘調用一次,或者說指定每天那個時間點執行。

  • jobDetail:定時任務的訊息,例如配置計時任務的名字,群組之類的。

  • job:定時任務的真正的業務處理邏輯的地方。

簡單範例

TestClient.Java

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

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")  //设置JOB的名字和组
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}

TaskJob.Java

import cn.hutool.core.date.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TaskJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("TaskJob => " + DateUtil.now());
    }
}

如何在Java中使用Quartz實作定時任務?

usingJobData

透過usingJobData 往定時任務中傳遞參數

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

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}

TaskJob.java

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

public class TaskJob implements Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        JobDataMap triggerMap = context.getTrigger().getJobDataMap();
        JobDataMap mergeMap = context.getMergedJobDataMap();


        System.out.println("jobDataMap => " + jobDataMap.getString("job"));
        System.out.println("triggerMap => " + triggerMap.getString("trigger"));
        System.out.println("mergeMap => " + mergeMap.getString("trigger"));
    }
}

如何在Java中使用Quartz實作定時任務?

透過屬性賦值

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

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .usingJobData("name","trigger.name.Value")  //如果 Trigger 有值,会覆盖 JobDetail
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}
import org.quartz.*;

public class TaskJob implements Job {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        System.out.println("name => " + name);
    }
}

非並發執行

@DisallowConcurrentExecution job類別上,禁止並發地執行同一個job定義(JobDetail定義的)的多個實例。

import cn.hutool.core.date.DateUtil;
import org.quartz.*;

@DisallowConcurrentExecution
public class TaskJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        System.out.println("Time => " + DateUtil.now());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@PersistJobDataAfterExecution

持久化JobDetail中的JobDataMap(對 trigger 中的 datamap 無效),如果一個任務不是

import cn.hutool.core.date.DateUtil;

import org.quartz.*;

//持久化JobDetail中的JobDataMap(对 trigger 中的 datamap 无效),如果一个任务不是
@PersistJobDataAfterExecution
public class TaskJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap triggerMap = context.getJobDetail().getJobDataMap();
        triggerMap.put("count", triggerMap.getInt("count") + 1);
        System.out.println("Time => " + DateUtil.now() + " count =>" + triggerMap.getInt("count"));

    }
}

Client

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

public class TaskClient {

    public static void main(String[] args) {
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("job","jobDetail1.JobDataMap.Value")
                .usingJobData("name","jobDetail1.name.Value") //通过 setName 自动赋值
                .usingJobData("count",0) //通过 setName 自动赋值
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "trigger1")
                .usingJobData("trigger","trigger.JobDataMap.Value")
                .usingJobData("name","trigger.name.Value")  //如果 Trigger 有值,会覆盖 JobDetail
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1)
                        .repeatForever())
                .build();
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.scheduleJob(jobDetail,trigger);
            scheduler.start();
        } catch (SchedulerException ex) {
            ex.printStackTrace();
        }

    }

}

以上是如何在Java中使用Quartz實作定時任務?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除