Web App使用Quartz实现java schedule job

2024-05-01 05:58

本文主要是介绍Web App使用Quartz实现java schedule job,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于Quartz

1 下载Quartz javacopyWEB-INF/lib

2 建立 scheduler初始化servlet

web.xml里加入

    <servlet>

            <servlet-name>Initializer</servlet-name>

            <servlet-class>

                com.nova.colimas.web.action.StartupServlet

            </servlet-class>

            <load-on-startup>1</load-on-startup>

   </servlet>

 

初始化servlet代码如下:

public class StartupServlet extends HttpServlet {

           

 

            public void init(ServletConfig cfg) throws

            javax.servlet.ServletException {

                        initScheduler(cfg);

                        return;

            }

 

           

            protected void initScheduler(ServletConfig cfg){

                        logger.info("Quartz Init Servlet loaded, initializing Scheduler...");

                       

                        // Start now

                        try{

            // Create an default instance of the Scheduler

                                    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

           //scheduler存入serlvet上下文。                cfg.getServletContext().setAttribute(Constants.SCHEDULER_KEY,scheduler);

                        }catch(Exception e){

                                    logger.error("Quartz Init Servlet failed");

                        }

 

            }

}

 

3 程序配置一个schedule job

 

/**

 * @author tyrone

 *

 * TODO To change the template for this generated type comment go to

 * Window - Preferences - Java - Code Style - Code Templates

 */

public class BatchEditAction extends Action implements PrivilegedAction {

            private static Logger logger = null;

            private Scheduler scheduler=null;

           

            public ActionForward execute(ActionMapping mapping,

                                     ActionForm form,

                                     HttpServletRequest request,

                                     HttpServletResponse response)

            throws Exception{

                        ActionMessages errors=new ActionMessages();

                        logger = Logger.getLogger(this.getClass());

//获得Servlet上下文

                                    ServletContext ctx =

                                                request.getSession().getServletContext();

                                   

//获得scheduler对象 

            scheduler=(Scheduler)ctx.getAttribute(Constants.SCHEDULER_KEY);

//根据form属性建立job                              

                                    createJob(form);

                                    try{

                                                logger.info("Scheduler starting up...");

                                                //启动scheduler

                                                scheduler.start();

                                    }catch(Exception e){

                                                logger.error("scheduler get error");

                                    }

 

                        return mapping.findForward("success");

            }

            /**

             * create a job based on form info.

             * @param form

             * @return

             */

            protected void createJob(ActionForm form) throws Exception{

                        BatchInfoForm batchinfo=(BatchInfoForm)form;

                        String classname=batchinfo.getFile();

                        SimpleTrigger sTrigger=null;

                        JobDetail jobDetail=null;

                        Calendar cal=null;

                       //如果是一天一次的job

                        if (batchinfo.getFrequency().equalsIgnoreCase("onceDaily")){

                                                logger.info("Batch run OnceDaily");                  

                                                cal = new AnnualCalendar();

                                                //Add Calendar to the Scheduler                      

                                                /*

                                                 * Setup a trigger to start firing now, with a null end date/time,

                                                 * repeat forever and have (hour*60+ minute)*60000 ms between each firing.

                                                 */
                                                //开始时间:

                                                String[] time=batchinfo.getDailyStartTime().split(":");

                                                java.util.Calendar rightNow = java.util.Calendar.getInstance();

                                                rightNow.set(java.util.Calendar.HOUR_OF_DAY,new Integer(time[0]).intValue());

                                                rightNow.set(java.util.Calendar.MINUTE,new Integer(time[1]).intValue());

                                              //间隔24小时

                                                long repeatInterval=24*60*60000;

                                                sTrigger = new SimpleTrigger("Trigger",

                                                                        Scheduler.DEFAULT_GROUP, rightNow.getTime(), null,

                                                                        SimpleTrigger.REPEAT_INDEFINITELY, repeatInterval);     

                                    }

                        }

 

                        // Trigger 关联一个Calendar, batchinfo.getName()唯一表示一个Calendar

                        sTrigger.setCalendarName(batchinfo.getName());

                        scheduler.addCalendar(batchinfo.getName(), cal, true, true);

                        try{

                            //job类名为com.nova.colimas.job.Test

                                    jobDetail = new JobDetail(classname,

                                                Scheduler.DEFAULT_GROUP, Class.forName(classname));

                                    //job关联一个Trigger,加入scheduler

                                    scheduler.scheduleJob(jobDetail, sTrigger);

                        }catch(ClassNotFoundException ex){

                                    logger.error(ex);

                                    throw new Exception();

                        }

                        return ;

            }

 

}

4 Job代码,job必须继承org.quartz.Job

package com.nova.colimas.job;

 

import org.apache.log4j.Logger;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

 

public class Test implements Job {

            private static Logger logger = null;

            public void execute(JobExecutionContext arg0) throws JobExecutionException {

                        // 定时运行。

                        logger = Logger.getLogger(this.getClass());

                        logger.info("test job is running");

            }

 

}

 

5 运行结果

 

[framework] 2005-08-23 11:45:29,440 - com.nova.colimas.job.Test -215700 [DefaultQuartzScheduler_Worker-0] INFO  com.nova.colimas.job.Test  - test job is running

这篇关于Web App使用Quartz实现java schedule job的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/950869

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ