java quartz timer_Java定时器Quartz和Timer
Java定時器之Quartz
簡介
官方說明
Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as support for JTA transactions and clustering.
Quartz是一個功能豐富的開源作業調度庫,它可以集成在幾乎任何Java應用程序中——從最小的獨立應用程序到最大的電子商務系統。Quartz可以用來創建簡單或復雜的調度,用于執行數十、數百甚至數萬個作業;任務被定義為標準的Java組件,實際上可以執行任何可以編程的任務。Quartz調度器包含許多企業級功能,例如對JTA事務和集群的支持。
調度操作demo
引入Quartz的jar包
org.quartz-scheduler
quartz
2.3.0
創建相關測試類
/**
* @program: java_demo
* @description:
* @author: Mr.Walloce
* @create: 2019/07/30 18:10
**/
public class QuartzTest {
/**
* @Description 測試job
* @Author Mr.Walloce
* @Date 2019/7/30 18:17
*/
public static class QuartzTestJob implements Job {
/**
* @Description TODO
* @param jobExecutionContext JobExecutionContext中包含了Quartz運行時的環境以及Job本身的詳細數據信息。
* @Return void
* @Author Mr.Walloce
* @Date 2019/7/29 19:17
*/
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("Quartz 測試任務被執行中...");
}
}
/**
* @Description 調度器(Simple Triggers)
* @param
* @Return void
* @Author Mr.Walloce
* @Date 2019/7/30 18:19
*/
public static void mySchedule() {
try {
//創建scheduler(調度器)實例
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//創建JobDetail實例,創建要執行的job
JobDetail jobDetail = JobBuilder.newJob(QuartzTestJob.class)
.withIdentity("job1", "group1").build();
//構建Trigger(觸發器)實例,每隔5s執行一次
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
//立即生效
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
//每隔5s執行一次
.withIntervalInSeconds(5)
//一直執行
.repeatForever())
.build();
//調度執行任務
scheduler.scheduleJob(jobDetail, trigger);
//啟動
scheduler.start();
//睡眠
//Thread.sleep(6000);
//停止
//scheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* @Description 調度器(Cron Triggers)
* @param
* @Return void
* @Author Mr.Walloce
* @Date 2019/7/29 18:59
*/
public static void myCronSchedule() {
try {
//創建調度器實例scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
JobDetail job = JobBuilder.newJob(QuartzTestJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
//20秒執行一次
.withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?"))
.build();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new QuartzTest().mySchedule();
}
}
**
以上兩種觸發器的形式調度任務,其中Cron Triggers需要使用到cron表達式
**
Quartzs結構說明
Job: 是一個接口,只定義一個方法execute(JobExecutionContext context),在實現接口的execute方法中編寫所需要定時執行的Job(任務), JobExecutionContext類提供了調度應用的一些信息。
JobDetail: Quartz每次調度Job時, 都重新創建一個Job實例, 所以它不直接接受一個Job的實例,相反它接收一個Job實現類。
Trigger:是一個類,描述觸發Job執行的時間觸發規則。主要有SimpleTrigger和CronTrigger這兩個子類。
Scheduler:代表一個Quartz的獨立運行容器, Trigger和JobDetail可以注冊到Scheduler中,擁有各自的組及名稱,組及名稱必須唯一(但可以和Trigger的組和名稱相同,因為它們是不同類型的)。Scheduler定義了多個接口方法, 允許外部通過組及名稱訪問和控制容器中Trigger和JobDetail。
Java定時器之Timer
簡介
Timer對象是在Java編程中常用到的定時計劃任務功能,它在內部使用多線程的方式進行處理,所以它和多線程技術還是有非常大的關聯的。在JDK中Timer類主要負責計劃任務的功能,也就是在指定的時間開始執行某一個任務,但封裝任務的類卻是TimerTask類。
TimerTask是實現接口Runnable的一個抽象類,即任務調度時是啟動一個新的線程來執行的。
public abstract class TimerTask implements Runnable
任務調度源碼解析
schedule(TimerTask task, Date time)
/**
* Schedules the specified task for execution at the specified time. If
* the time is in the past, the task is scheduled for immediate execution.
*
* @param task task to be scheduled.
* @param time time at which task is to be executed.
* @throws IllegalArgumentException if time.getTime() is negative.
* @throws IllegalStateException if task was already scheduled or
* cancelled, timer was cancelled, or timer thread terminated.
* @throws NullPointerException if {@code task} or {@code time} is null
*/
public void schedule(TimerTask task, Date time) {
sched(task, time.getTime(), 0);
}
**
以上又參數說明可以看出該方法是指在指定的時間開始調度指定的任務
task:被調度執行的任務
time:任務開始調度執行的時間
該方法任務調度,只調度執行一次
**
schedule(TimerTask task, long delay, long period)
/**
* Schedules the specified task for repeated fixed-delay execution,
* beginning after the specified delay. Subsequent executions take place
* at approximately regular intervals separated by the specified period.
*
*
In fixed-delay execution, each execution is scheduled relative to
* the actual execution time of the previous execution. If an execution
* is delayed for any reason (such as garbage collection or other
* background activity), subsequent executions will be delayed as well.
* In the long run, the frequency of execution will generally be slightly
* lower than the reciprocal of the specified period (assuming the system
* clock underlying Object.wait(long) is accurate).
*
*
Fixed-delay execution is appropriate for recurring activities
* that require "smoothness." In other words, it is appropriate for
* activities where it is more important to keep the frequency accurate
* in the short run than in the long run. This includes most animation
* tasks, such as blinking a cursor at regular intervals. It also includes
* tasks wherein regular activity is performed in response to human
* input, such as automatically repeating a character as long as a key
* is held down.
*
* @param task task to be scheduled.
* @param delay delay in milliseconds before task is to be executed.
* @param period time in milliseconds between successive task executions.
* @throws IllegalArgumentException if {@code delay < 0}, or
* {@code delay + System.currentTimeMillis() < 0}, or
* {@code period <= 0}
* @throws IllegalStateException if task was already scheduled or
* cancelled, timer was cancelled, or timer thread terminated.
* @throws NullPointerException if {@code task} is null
*/
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, System.currentTimeMillis()+delay, -period);
}
**
設定延遲調度任務及連續執行的時長
delay:延遲調度的時長(毫秒)
period:連續執行的時長(毫秒,任務執行時間間隔)
調度任務執行多次
**
schedule(TimerTask task, long delay)
/**
* Schedules the specified task for execution after the specified delay.
*
* @param task task to be scheduled.
* @param delay delay in milliseconds before task is to be executed.
* @throws IllegalArgumentException if delay is negative, or
* delay + System.currentTimeMillis() is negative.
* @throws IllegalStateException if task was already scheduled or
* cancelled, timer was cancelled, or timer thread terminated.
* @throws NullPointerException if {@code task} is null
*/
public void schedule(TimerTask task, long delay) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
sched(task, System.currentTimeMillis()+delay, 0);
}
**
延遲執行任務調度
delay:延遲調度的時長(毫秒)
任務調度只執行一次
**
schedule(TimerTask task, Date firstTime, long period)
/**
* Schedules the specified task for repeated fixed-delay execution,
* beginning at the specified time. Subsequent executions take place at
* approximately regular intervals, separated by the specified period.
*
*
In fixed-delay execution, each execution is scheduled relative to
* the actual execution time of the previous execution. If an execution
* is delayed for any reason (such as garbage collection or other
* background activity), subsequent executions will be delayed as well.
* In the long run, the frequency of execution will generally be slightly
* lower than the reciprocal of the specified period (assuming the system
* clock underlying Object.wait(long) is accurate). As a
* consequence of the above, if the scheduled first time is in the past,
* it is scheduled for immediate execution.
*
*
Fixed-delay execution is appropriate for recurring activities
* that require "smoothness." In other words, it is appropriate for
* activities where it is more important to keep the frequency accurate
* in the short run than in the long run. This includes most animation
* tasks, such as blinking a cursor at regular intervals. It also includes
* tasks wherein regular activity is performed in response to human
* input, such as automatically repeating a character as long as a key
* is held down.
*
* @param task task to be scheduled.
* @param firstTime First time at which task is to be executed.
* @param period time in milliseconds between successive task executions.
* @throws IllegalArgumentException if {@code firstTime.getTime() < 0}, or
* {@code period <= 0}
* @throws IllegalStateException if task was already scheduled or
* cancelled, timer was cancelled, or timer thread terminated.
* @throws NullPointerException if {@code task} or {@code firstTime} is null
*/
public void schedule(TimerTask task, Date firstTime, long period) {
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, firstTime.getTime(), -period);
}
**
首次調度任務的時間及調度時長
firstTime:首次執行調度的時間
period:連續執行的時長(毫秒,任務執行時間間隔)
設定首次執行的時間后,調度多次執行任務
**
任務調度實例
package com.timer;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @program: java_demo
* @description: Java中Timer定時器測試
* @author: Mr.Walloce
* @create: 2019/07/29 22:36
**/
public class TimerTest {
public static class MyTimer extends TimerTask {
/**
* The action to be performed by this timer task.
*/
public void run() {
//任務執行的邏輯代碼塊
System.out.println("任務被調度執行...");
}
}
public static void main(String[] args) {
Timer t = new Timer();
MyTimer mt = new MyTimer();
//立即執行
//t.schedule(mt, new Date());
//5s后執行
//t.schedule(mt, 5000);
//5s 后執行,每2s執行一次
//t.schedule(mt, 5000, 2000);
//每2s執行一次
t.schedule(mt, new Date(), 2000);
}
}
Quartz和Timer對比
Quartz
非常靈活,可以使用多種形式的定時方式
非常輕量級,而且只需要很少的設置/配置
是容錯的,在系統重啟后記住以前的記錄
可以參與事務
Timer
定時器沒有持久性機制
創建方便簡單,不用另外引入jar包
**
以上為Quartz和Timer兩種定時器的簡單用法和比較,如有不足或錯誤,希望補充或指正!
**
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的java quartz timer_Java定时器Quartz和Timer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 泛型机制_java中的泛型机制
- 下一篇: java 生成objectid_【Jav