zoukankan      html  css  js  c++  java
  • 定时任务

    我知道的实现定时任务功能的方式目前有以下几种
    方式一:使用java.util下的Timer和TimerTask,单线程。
    入门demo:
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
       @Override
       public void run() {
           System.out.println("hello");
       }
    },10000,1000);        
    方式二:使用Executors.newScheduledThreadPool(5),可多线程。
    入门demo:
    ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
    service.scheduleAtFixedRate(()->{
        System.out.println(Thread.currentThread().getName());
    },10,2, TimeUnit.SECONDS);
    service.scheduleAtFixedRate(()->{
        System.out.println(Thread.currentThread().getName());
    },10,2, TimeUnit.SECONDS);
    service.scheduleAtFixedRate(()->{
        System.out.println(Thread.currentThread().getName());
    },10,2, TimeUnit.SECONDS);    
    方式三:使用Spring-Task,不支持集群。
    入门demo(xml方式):
      步骤一:写一个执行任务的类:
    package com.hello.jianwu;
    import org.springframework.stereotype.Component;
    @Component
    public class TaskOne {
    public void job(){
    System.out.println("hello");
    }
    }

      步骤二:在applicationContext.xml中配置

    <context:component-scan base-package="com.qukan.jianwu" />
    <task:scheduled-tasks>
       <task:scheduled ref="taskOne" method="job" cron="0/5 * * * * ? "/>
    </task:scheduled-tasks>

    入门demo(注解方式):

    步骤一:写一个执行任务的类:
    package com.hello.jianwu;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    @Component
    public class TaskOne {
        @Scheduled(cron = "0/5 * * * * ?")
        public void job() {
            System.out.println("hello");
        }
    }

      步骤二:在applicationContext.xml中配置

    <context:component-scan base-package="com.qukan.jianwu" />
    <task:annotation-driven />
    方式四:使用spring的@scheduled注解,不支持集群,当在多台机器上运行时,需要自己使用数据库或redis等加锁的方式控制只能一台机器运行。

    方式五:使用Quartz,支持集群。
  • 相关阅读:
    信息化基础建设 ORM 常见错误
    信息化基础建设 消息引擎
    Enterprise Library:日志的两种需求
    DDD:将概念显式化 之 验证规约
    技术人生:与其鸟宿檐下,不如击翅风雨
    DDD:传统三层架构向DDD的转换
    设计原则:意图导向编程的优点
    Entity Framework:数据库初始化的三种机制
    技术人生:使用价值观、原则和模式来理性的做设计和编程
    技术人生:人的差别在于业余时间
  • 原文地址:https://www.cnblogs.com/ENU7/p/9480286.html
Copyright © 2011-2022 走看看