java常用定時組件

java 定時組件

  1. cron4j

    cron4j是輕量級的定時組件,可使用linux的crontab表達式來配置線程執行的時間。官方說,可以保證一年內的時間正確性。最小定時精度是一分鐘。官網:http://www.sauronsoftware.it/projects/cron4j/manual.php


稍微看了下源碼,大概是線程每次休眠一分鐘,然後查看有沒有到可以執行的時間。如果到了就執行,否則,繼續休眠。 下面是官方文檔上摘錄的一些關鍵概念。
You can schedule how many tasks you want.
You can schedule a task when you want, also after the scheduler has been started.
**You can change the scheduling pattern of an already scheduled task**, also while the scheduler is running (reschedule operation).
You can remove a previously scheduled task, also while the scheduler is running (deschedule operation).
You can start and stop a scheduler how many times you want.
You can schedule from a file.
You can schedule from any source you want.
You can supply listeners to the scheduler in order to receive events about the executed task.
You can control any ongoing task.
You can manually launch a task, without using a scheduling pattern.
You can change the scheduler working Time Zone.
You can validate your scheduling patterns before using them with the scheduler.
You can predict when a scheduling pattern will cause a task execution.
一個簡單的例子:
import it.sauronsoftware.cron4j.Scheduler;

public class Quickstart {

    public static void main(String[] args) {
        Scheduler s = new Scheduler();
        // Schedule a once-a-minute task.
        s.schedule("* * * * *", new Runnable() {
            public void run() {
                System.out.println("Another minute ticked away...");
            }
        });
        // Starts the scheduler.
        s.start();
        // Will run for ten minutes.
        try {
            Thread.sleep(1000L * 60L * 10L);
        } catch (InterruptedException e) {
            ;
        }
        // Stops the scheduler.
        s.stop();
    }
}
  • 引用的依賴
<dependency>
    <groupId>it.sauronsoftware.cron4j</groupId>
    <artifactId>cron4j</artifactId>
    <version>2.2.5</version>
</dependency>

2.Quartz

Quartz是OpenSymphony開源組織在Jobscheduling領域一個開源項目,Quartz可以用來創建簡單或爲運行數百個,甚至是好幾萬個Jobs這樣複雜的程序。Jobs可以做成標準的Java組件或EJBs。
Quartz的核心是調度器,他有自己的線程池,可以併發地執行多個作業。框架也是鬆耦合的,可以替換裏面的組件。官網:http://www.quartz-scheduler.org/

  • quartz提供了豐富的監聽器,可以在任務被調度,被終止等情況觸發。
  • quartz支持集羣。可支持負載均衡,高可用等。

  • 引用的依賴

<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>

2.2 quartz起步

定時調度框架的幾個概念,任務Job,調度器Schedule,觸發器Trigger(決定什麼時候調度任務)。quartz包含幾種調度器:最簡單的什麼時候執行,執行幾次,多久執行一次。複雜的支持cron表達式。

  • Trigger有優先級的概念,因爲框架使用線程池調度任務,但是當有大量的任務需要被同時調度時,這個優先級就可以決定調度的順序。
  • Calendars不是java中通常的Calendars概念。Calendars可以排除掉某些特定的天。比如需要一個任務每天上午9:30執行,但是節假日又不想運行。就可以使用Calendars排除掉節假日。

下面是一個簡單的例子:

package com.step.jliang.quartz;

import com.step.jliang.quartz.job.HelloJob;
import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

public class HelloQuartzScheduling {

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

        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        JobDetail helloJob = new JobDetailImpl("helloQuartzJob",
                Scheduler.DEFAULT_GROUP, HelloJob.class);

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
                .withSchedule(simpleSchedule().
                        repeatSecondlyForever())
                .build();

        scheduler.scheduleJob(helloJob, trigger);
        scheduler.start();
        try {
            Thread.sleep(1000 * 60 * 3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

推薦一篇比較好的博客.但是因爲博客引用的api比較老,很多例子跑不起來,但是講的還是很好的。quartz博客

3.spring框架的@Schedule

如果使用spring框架,再使用定時任務就很簡單了。spring提供了對cron表達式的支持。只需要在定時任務上,通過@Schedule就可以。還可以配置自己的任務線程池。

具體可參考這篇博客spring定時任務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章