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();

    }

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

猜你喜欢

转载自www.cnblogs.com/wumingxuanji/p/9081502.html