搜索
首页Javajava教程定时器的实现、java定时器Timer和Quartz介绍与Spring中定时器的配置

1定时器的作用
在实际的开发中,如果项目中需要定时执行或者需要重复执行一定的工作,定时器显现的尤为重要。
当然如果我们不了解定时器就会用线程去实现,例如:
package org.lzstone.action
public class FinanceAction extends Thread{
       private Date date;
       public void run{
       try{
       while(true){
       Thread.sleep((int)(Math.random()*1000));
       date = new Date();
       //定时执行任务
       }
       }catch(Exception e){
        e.printStackTrace();
       }
}
}
自己实现定时器的工作很复杂,如果实现不好占用内存过多,系统就此Over,所以处理定时执行或者重复执行的任务,定时器是很好的选择
2.java中常见的定时器
1)借助Java.util.Timer来实现
2)OpenSymphony社区提供的Quartz来实现
3.介绍Timer
利用Timer开发定时任务是主要分为两个步骤:
1)创建定时任务类
示例代码:
package org.lzstone.action
import java.util.TimeTask
public class LzstoneTimeTask extends TimeTask{
       public void run(){
              //执行的定时器任务
       }
}
2)运行定时任务,运行定时任务分为两种方式:
2.1)程序直接启动
示例代码:
package org.lzstone.action
public class LzstoneMain{
       .......
       public void run(){
        //执行定时器的任务
        //创建实例
        Timer timer = new Timer();
        参数:
        new LzstoneTimeTask()- 所要安排的任务。
        0- 执行任务前的延迟时间,单位是毫秒。
        1*1000- 执行各后续任务之间的时间间隔,单位是毫秒。
        timer.schedule(new LzstoneTimeTask(),0,1*1000);
       }
}
2.2)web监听方式
示例代码:
package org.lzstone.action
public class LzstoneMain implements ServletContextListener{
       private Timer timer = null;
       //初始化监听器,创建实例,执行任务
       public void contextInitialized(ServletContextEvent event){
               timer = new Timer();
               timer.schedule(new LzstoneTimeTask(),0,1*1000);
       }
       //销毁监听器,停止执行任务
       public void contextDestroyed(ServletContextEvent event){
              //注意,在此计时器调用的计时器任务的 run 方法内调用此方法,就可以绝对确保正在执行的任务是此计时器所执行的最后一个任务。
              timer.cancel();
        }
}
web.xml配置

  
        org.lzstone.action.LzstoneMain
  


4. 介绍Quartz
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,可以用来创建简单或者复杂的定时任务,利用Quartz开发定时任务的步骤与Timer类

似。

利用Quartz开发定时任务是主要分为两个步骤:
1)创建定时任务类
示例代码:
package org.lzstone.action
public class LzstoneTimeTask implements Job{
       public void execute(JobExecutionContext context) throws JobExecutionException{
              //执行的定时器任务
       }
}
2)运行定时任务,运行定时任务分为两种方式:
2.1)程序直接启动,创建任务调度器及配置相应的任务计划
示例代码:
package org.lzstone.action
public class LzstoneMain{
       private static Scheduler sched;
       public static void run() throws Exception{
              //创建LzstoneTimeTask的定时任务
              JobDetail jobDetail = new JobDetail("lzstoneJob",sched.DEFAULT_GROUP,LzstoneTimeTask.class);
              //目标 创建任务计划
              CronTrigger trigger = new CronTrigger("lzstoneTrigger","lzstone","0 0 12 * * ?");
              //0 0 12 * * ? 代表每天的中午12点触发
              sched = new org.quartz.impl.StdSchedulerFactory().getScheduler();
              sched.scheduleJob(jobDetail,trigger);
              sched.start();
       }
       //停止
       public static void stop() throws Exception{
              sched.shutdown();
        }
}
//执行
public class Main{
       .............
       public void run(){
            LzstoneMain.run();
       }
       ............
}
2.2)web监听方式
示例代码:
package org.lzstone.action
public class LzstoneMainListener implements ServletContextListener{
       private Timer timer = null;
       //初始化监听器,创建实例,执行任务
       public void contextInitialized(ServletContextEvent event){
               LzstoneMain.run();
       }
       //销毁监听器,停止执行任务
       public void contextDestroyed(ServletContextEvent event){
              LzstoneMain.stop();
        }
}
web.xml配置

  
        org.lzstone.action.LzstoneMainListener
  


5.对比
Timer方式实现定时器,原理简单,实现方便,在执行简单的任务比较方便,不足之处是无法确定执行时间,并且依赖性比较强,必须继承指定的类
Quartz方式实现定时器,方便,清晰指定启动时间,定时参数比较灵活,容易实现比较复杂的定时任务,不足之处是需要实现特定接口,加载其框架
两种方式各有优缺点,在特定场合可以根据其特点选择使用。
6.Spring定时任务
Spring定时任务对Timer与Quartz都提供了支持,并且实现步骤基本一样
首先配置Spring对Timer的支持
1.1 创建定时任务类
package org.lzstone.action
import java.util.TimeTask
public class LzstoneTimeTask extends TimeTask{
       public void run(){
              //执行的定时器任务
       }
}
1.2 注册定时任务类,配置任务计划与任务调度器
    在项目的WEB-INF下面创建TimerConfig.xml文件(一般叫做applicationContext.xml)










3000



  4000










   
       
        ........
   




1.3 web项目中的启动设置
   
      contextConfigLocation
      /WEB-INF/TimerConfig.xml
    


    
        
                  org.springframework.web.context.ContextLoaderListener
        

    

配置Spring对Quartz的支持
2.1 创建定时任务类
package org.lzstone.action
public class LzstoneQuartzTask{
       public void execute(){
              //执行的定时器任务
       }
}
2.2 注册定时任务类,配置任务计划与任务调度器
    在项目的WEB-INF下面创建QuartzConfig.xml文件(一般叫做applicationContext.xml)














execute






   



    0 0 12 * * ?






   
         
   




2.3 web项目中的启动设置
   
      contextConfigLocation
      /WEB-INF/QuartzConfig.xml
    


    
        
                  org.springframework.web.context.ContextLoaderListener
        

    




更多定时器的实现、java定时器Timer和Quartz介绍与Spring中定时器的配置相关文章请关注PHP中文网!


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。