Scheduled Jobs with Custom Clock Processes in Java with Quartz and RabbitMQ

原文地址: https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes-java-quartz-rabbitmq

 

Table of Contents

There are numerous ways to schedule background jobs in Java applications. This article will teach you how to setup a Java application that uses the Quartz library along with RabbitMQ to create a scalable and reliable method of scheduling background jobs on Heroku.

Many of the common methods for background processing in Java advocate running background jobs within the same application as the web tier. This approach has scalability and reliability constraints.

A better approach is to move background jobs into separate processes so that the web tier is distinctly separate from the background processing tier. This allows the web tier to be exclusively for handling web requests. The scheduling of jobs should also be it’s own tier that puts jobs onto a queue. The worker processing tier can then be scaled independently from the rest of the application.

If you have questions about Java on Heroku, consider discussing them in the Java on Heroku forums.

The source for this article's reference application is available on GitHub.

Prerequisites

To clone the sample project to your local computer run:

$ git clone https://github.com/heroku/devcenter-java-quartz-rabbitmq.git
Cloning into devcenter-java-quartz-rabbitmq...

$ cd devcenter-java-quartz-rabbitmq/

Scheduling jobs with Quartz

custom clock process will be used to create jobs and add them to a queue. To setup a custom clock process use the Quartz library. In Maven the dependency is declared with:

See the reference app's pom.xml for the full Maven build definition.

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.1.5</version>
</dependency>

Now a Java application can be used to schedule jobs. Here is an example:

package com.heroku.devcenter;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {

    final static Logger logger = LoggerFactory.getLogger(SchedulerMain.class);

    public static void main(String[] args) throws Exception {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();

        JobDetail jobDetail = newJob(HelloJob.class).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(repeatSecondlyForever(2))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    public static class HelloJob implements Job {

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            logger.info("HelloJob executed");
        }
    }
}

This simple example creates a HelloJob every two seconds that simply logs a message. Quartz has a very extensive API for creating Triggerschedules.

To test this application locally you can run the Maven build and then run the SchedulerMain Java class:

$ mvn package
INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building devcenter-java-quartz-rabbitmq 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------

$ java -cp target/classes:target/dependency/* com.heroku.devcenter.SchedulerMain
...
66 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
66 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 2.1.5
66 [main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
104 [DefaultQuartzScheduler_Worker-1] INFO com.heroku.devcenter.SchedulerMain - HelloJob executed
2084 [DefaultQuartzScheduler_Worker-2] INFO com.heroku.devcenter.SchedulerMain - HelloJob executed

Press Ctrl-C to exit the app.

If the HelloJob actually did work itself then we would have a runtime bottleneck because we could not scale the scheduler while avoiding duplicate jobs being scheduled. Quartz does have a JDBC module that can use a database to prevent jobs from being duplicated but a simpler approach is to only run one instance of the scheduler and have the scheduled jobs added to a message queue where they can be processes in parallel by job worker processes.

Queuing jobs with RabbitMQ

RabbitMQ can be used as a message queue so the scheduler process can be used just to add jobs to a queue and worker processes can be used to grab jobs from the queue and process them. To add the RabbitMQ client library as a dependency in Maven specify the following in dependencies block of the pom.xml file:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>2.8.2</version>
</dependency>

If you want to test this locally then install RabbitMQ and set an environment variable that will provide the application the connection information to your RabbitMQ server.

On Windows:

$ set CLOUDAMQP_URL="amqp://guest:guest@localhost:5672/%2f"

On Mac/Linux:

$ export CLOUDAMQP_URL="amqp://guest:guest@localhost:5672/%2f"

The CLOUDAMQP_URL environment variable will be used by the scheduler and worker processes to connect to the shared message queue. This example uses that environment variable because that is the way theCloudAMQP Heroku Add-on will provide it’s connection information to the application.

The SchedulerMain class needs to be updated to add a new message onto a queue every time the HelloJob is executed. Here are the newSchedulerMain and HelloJob classes from the SchedulerMain.java file in the sample project:

package com.heroku.devcenter;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {

    final static Logger logger = LoggerFactory.getLogger(SchedulerMain.class);
    final static ConnectionFactory factory = new ConnectionFactory();

    public static void main(String[] args) throws Exception {
        factory.setUri(System.getenv("CLOUDAMQP_URL"));
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();

        JobDetail jobDetail = newJob(HelloJob.class).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(repeatSecondlyForever(5))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    public static class HelloJob implements Job {

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

            try {
                Connection connection = factory.newConnection();
                Channel channel = connection.createChannel();
                String queueName = "work-queue-1";
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("x-ha-policy", "all");
                channel.queueDeclare(queueName, true, false, false, params);

                String msg = "Sent at:" + System.currentTimeMillis();
                byte[] body = msg.getBytes("UTF-8");
                channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, body);
                logger.info("Message Sent: " + msg);
                connection.close();
            }
            catch (Exception e) {
                logger.error(e.getMessage(), e);
            }

        }

    }

}

In this example every time the HelloJob is executed it adds a message onto a RabbitMQ message queue simply containing a String with the time the String was created. Running the updated SchedulerMainshould add a new message to the queue every 5 seconds.

Processing jobs

Next, create a Java application that will pull messages from the queue and handle them. This application will also use the RabbitFactoryUtilto get a connection to RabbitMQ from the CLOUDAMQP_URL environment variable. Here is the WorkerMain class from the WorkerMain.java file in the example project:

package com.heroku.devcenter;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class WorkerMain {

    final static Logger logger = LoggerFactory.getLogger(WorkerMain.class);

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

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(System.getenv("CLOUDAMQP_URL"));
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String queueName = "work-queue-1";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("x-ha-policy", "all");
        channel.queueDeclare(queueName, true, false, false, params);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, false, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            if (delivery != null) {
                String msg = new String(delivery.getBody(), "UTF-8");
                logger.info("Message Received: " + msg);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }

    }

}

This class simply waits for new messages on the message queue and logs that it received them. You can run this example locally by doing a build and then running the WorkerMain class:

$ mvn package
$ java -cp target/classes:target/dependency/* com.heroku.devcenter.WorkerMain

You can also run multiple instances of this example locally to see how the job processing can be horizontally distributed.

Running on Heroku

Now that you have everything working locally you can run this on Heroku. First declare the process model in a new file named Procfilecontaining:

scheduler: java $JAVA_OPTS -cp target/classes:target/dependency/* com.heroku.devcenter.SchedulerMain
worker: java $JAVA_OPTS -cp target/classes:target/dependency/* com.heroku.devcenter.WorkerMain

This defines two process types that can be executed on Heroku; one named scheduler for the SchedulerMain app and one named workerfor the WorkerMain app.

To run on Heroku you will need to push a Git repository to Heroku containing the Maven build descriptor, source code, and Procfile. If you cloned the example project then you already have a Git repository. If you need to create a new git repository containing these files, run:

$ git init
$ git add src pom.xml Procfile
$ git commit -m init

Create a new application on Heroku from within the project’s root directory:

$ heroku create
Creating furious-cloud-2945... done, stack is cedar-14
http://furious-cloud-2945.herokuapp.com/ | git@heroku.com:furious-cloud-2945.git
Git remote heroku added

Then add the CloudAMQP add-on to your application:

$ heroku addons:add cloudamqp
Adding cloudamqp to furious-cloud-2945... done, v2 (free)
cloudamqp documentation available at: https://devcenter.heroku.com/articles/cloudamqp

Now push your Git repository to Heroku:

$ git push heroku master
Counting objects: 165, done.
Delta compression using up to 2 threads.
...
-----> Heroku receiving push
-----> Java app detected
...
-----> Discovering process types
       Procfile declares types -> scheduler, worker
-----> Compiled slug size is 1.4MB
-----> Launching... done, v5
       http://furious-cloud-2945.herokuapp.com deployed to Heroku

This will run the Maven build for your project on Heroku and create a slug file containing the executable assets for your application. To run the application you will need to allocate dynos to run each process type. You should only allocate one dyno to run the scheduler process type to avoid duplicate job scheduling. You can allocate as many dynos as needed to the worker process type since it is event driven and parallelizable through the RabbitMQ message queue.

To allocate one dyno to the scheduler process type run:

$ heroku ps:scale scheduler=1
Scaling scheduler processes... done, now running 1

This should begin adding messages to the queue every five seconds. To allocate two dynos to the worker process type run:

$ heroku ps:scale worker=2
Scaling worker processes... done, now running 2

This will provision two dynos, each which will run the WorkerMain app and pull messages from the queue for processing. You can verify that this is happening by watching the Heroku logs for your application. To open a feed of your logs run:

$ heroku logs -t
2012-06-26T22:26:47+00:00 app[scheduler.1]: 100223 [DefaultQuartzScheduler_Worker-1] INFO com.heroku.devcenter.SchedulerMain - Message Sent: Sent at:1340749607126
2012-06-26T22:26:47+00:00 app[worker.2]: 104798 [main] INFO com.heroku.devcenter.WorkerMain - Message Received: Sent at:1340749607126
2012-06-26T22:26:52+00:00 app[scheduler.1]: 105252 [DefaultQuartzScheduler_Worker-2] INFO com.heroku.devcenter.SchedulerMain - Message Sent: Sent at:1340749612155
2012-06-26T22:26:52+00:00 app[worker.1]: 109738 [main] INFO com.heroku.devcenter.WorkerMain - Message Received: Sent at:1340749612155

In this example execution the scheduler creates 2 messages which are handled by the two different worker dynos (worker.1 and worker.2). This shows that the work is being scheduled and distributed correctly.

Further learning

This example application just shows the basics for architecting a scalable and reliable system for scheduling and processing background jobs. To learn more see:

 

时间: 2024-10-02 22:53:20

Scheduled Jobs with Custom Clock Processes in Java with Quartz and RabbitMQ的相关文章

java中quartz调度在一些定时任务(job)的入门级应用

Quartz 执行详解:http://quartz-scheduler.org/   去下载相应的jar包 在maven中可直接把依赖拷贝过来复制到pom中去. 具体规则可查询quartz的文档 下面是一个非常详细的实例: 1.首先把需要执行的任务写到execute中去 并实现job package job; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import or

java中Quartz 语法整理

Quartz cron 表达式的格式十分类似于 UNIX cron 格式,但还是有少许明显的区别.区别之一就是 Quartz 的格式向下支持到秒级别的计划,而 UNIX cron 计划仅支持至分钟级.许多我们的触发计划要基于秒级递增的(例如,每45秒),因此这是一个非常好的差异. 在 UNIX cron 里,要执行的作业(或者说命令)是存放在 cron 表达式中的,在第六个域位置上.Quartz 用 cron 表达式存放执行计划.引用了 cron 表达式的CronTrigger 在计划的时间里会

最流行的java后台框架spring quartz定时任务_java

配置quartz 在spring中需要三个jar包: quartz-1.8.5.jar.commons-collections-3.2.1.jar.commons-logging-1.1.jar 首先要配置我们的spring.xml xmlns 多加下面的内容. xmlns:task="http://www.springframework.org/schema/task"  然后xsi:schemaLocation多加下面的内容. http://www.springframework.

SpringBoot开发案例之整合定时任务(Scheduled)

来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中. 不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现. 任务介绍 Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务.Timer的优点在于简单易用:缺点是Timer的所有任务都是由同一个线程调度的,因此所有任务都是串行执行的.同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任

Java面试笔试题大汇总(最全+详细答案)

声明:有人说, 有些面试题很变态,个人认为其实是因为我们基础不扎实或者没有深入.本篇文章来自一位很资深的前辈对于最近java面试题目所做的总结归纳,有170道题目 ,知识面很广 ,而且这位前辈对于每个题都自己测试给出了答案 ,如果你对某个题有疑问或者不明白,可以电脑端登录把题目复制下来然后发表评论,大家一起探讨,也可以电脑端登录后关注我给我发私信,我们一起进步! 以下内容来自这位前辈 2013年年底的时候,我看到了网上流传的一个叫做<Java面试题大全>的东西,认真的阅读了以后发现里面的很多题

Java面试必看二十问题

大家都应该知道Java是目前最火的计算机语言之一,连续几年蝉联最受程序员欢迎的计算机语言榜首,因此每年新入职Java程序员也数不胜数.究竟这些新入职的Java程序员是入坑还是入行呢?那就要看他们对于Java这门语言的看法了.不管如何,在入职之前,问题会要经过面试,那么Java面试题是怎么出的呢?下面罗列了20道常见初级Java面试题,简直是入职者必备! 1.面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面: - 抽象:抽象是将一类对象的共同特征总结出来构造类的过程,包括数据抽象和

(RabbitMQ) Java Client API Guide

本篇翻译的是RabbitMQ官方文档关于API的内容,原文链接:http://www.rabbitmq.com/api-guide.html.博主对其内容进行大体上的翻译,有些许部分会保留英文,个人觉得这样更加有韵味,如果全部翻译成中文,会存在偏差,文不达意(主要是功力浅薄~~).文章也对部分内容进行一定的解释,增强对相关知识点的理解. Overview RabbitMQ java client uses com.rabbitmq.client as its top-level package,

java.net.UnknownHostException和javax.mail.MessagingException的问题

问题描述 javax.mail.MessagingException:UnknownSMTPhost:mail02.secpg.com;nestedexceptionis:java.net.UnknownHostException:mail02.secpg.comatcom.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1225)atcom.sun.mail.smtp.SMTPTransport.protocolConnect

【Spring】定时任务详解实例-@Scheduled

转载请注明出处http://blog.csdn.net/qq_26525215 本文源自[大学之旅_谙忆的博客] 最近在做项目时间比较紧张也有比较久没写博客了. 现在项目的Redis缓存需要用到定时任务就学习了一下Spring 的@Scheduled注解.使用起来很简单. 这个例子是建立在之前我的一篇博客的实例上面的. 也就是架好了SSM框架. SSM框架博客的链接 [->点击访问上篇博客源码-CHX] 首先当然是在Spring的xml配置文件加入task的命名空间 xmlns:task="