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

    java中的定时任务 一般有三种实现方式:

    1,普通的线程thread

    @Test
      public void test1() {  
            // 单位: 毫秒
            final long timeInterval = 1000;  
            Runnable runnable = new Runnable() {  
                public void run() {  
                    while (true) {  
                        // ------- code for task to run  
                        System.out.println("Hello !!");  
                        // ------- ends here  
                        try {  
                            Thread.sleep(timeInterval);  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            };  
            Thread thread = new Thread(runnable);  
            thread.start();  
        } 

    2,使用timer实现:可控制启动或取消任务,可指定第一次执行的延迟,线程安全, 但只会单线程执行, 如果执行时间过长, 就错过下次任务了, 抛出异常时, timerWork会终止

    @Test
    public void test2 () {  
          TimerTask task = new TimerTask() {  
              @Override  
              public void run() {  
                 System.out.println("Hello !!!");  
              }  
          };  
          Timer timer = new Timer();  
          long delay = 0;  
          long intevalPeriod = 1 * 1000;  
          // schedules the task to be run in an interval  
          timer.scheduleAtFixedRate(task, delay, intevalPeriod);  
        }

    3,使用spring 的spring-task实现   这里我只说我项目中的使用方法,配置文件配置的方式:

    在spring配置文件里配置:

    <!—开启这个配置,spring才能识别@Scheduled注解   -->  
        <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
        <task:scheduler id="qbScheduler" pool-size="10"/> 

    而配置好之后  就是java代码的实现

    @Scheduled(fixedDelay = 600000) //fixedRate是每隔n毫秒数执行一次任务,fixedDelay是上个任务执行完成后每隔n毫秒数执行一次任务。
        public void task5() throws Exception {
            List<UserInfo> userList = userInfoService.handleGetUserinfoPlat();
    
        }

    我们使用的是 第三种以配置文件的方式实现的定时任务,至于前面两种我是参考别的博客,拷贝的,

  • 相关阅读:
    php高效率写法
    php经典bug
    cideogniter部署到阿里云服务器出现session加载错误
    linux gcc编译protocol
    linux权限问题
    http协议详解
    哈希表
    c语言函数
    socket相关函数
    构建之法阅读笔记05
  • 原文地址:https://www.cnblogs.com/wumingxuanji/p/9081502.html
Copyright © 2011-2022 走看看