Ver Mensaje Individual
  #3 (permalink)  
Antiguo 29/03/2012, 06:50
Avatar de goncafa
goncafa
 
Fecha de Ingreso: julio-2002
Ubicación: Santiago
Mensajes: 1.211
Antigüedad: 21 años, 10 meses
Puntos: 10
Respuesta: programa no finaliza timer

Asi es el funcionamiento de la clase timer.

Yo la he usado algunas veces y siempre invoco a cancel al final del metodo run del timer.

Te dejo aqui una implementacion que realize hace poco de un Timer que necesitaba para mi aplicacion, espero te sirva.

Código PHP:
/*
 * Copyright (C) 2012 by Gonzalo Castillo
 * This software is provided under the GNU general public license (http://www.gnu.org/copyleft/gpl.html).
 */
package com.goncafa.proxy.util;

import java.util.TimerTask;

public class 
Timer {
    private 
java.util.Timer timer;
    private 
TimeoutListener timeoutListener;
    private 
boolean timeout;
    
    public 
Timer() {
        
super();
        
this.timeout false;
    }
    
    public 
Timer(Long millis) {
        
this();
        
this.schedule(millis);
    }
    
    public 
Timer(Long millisTimeoutListener timeOutListener) {
        
this(millis);
        
this.addTimeOutListener(timeOutListener);
    }
    
    public 
void addTimeOutListener(TimeoutListener timeOutListener) {
        if (
timeOutListener == null) {
            throw new 
NullPointerException();
        }
        
        
this.timeoutListener timeOutListener;
    }
    
    public 
void schedule(Long millis) {
        if (
this.timer != null) {
            
this.cancel();
            
this.timer null;
        }
        
        
this.timeout false;
        
        
this.timer = new java.util.Timer();
        
this.timer.schedule(new TimerTask() {
            @
Override
            
public void run() {
                
timeout();
            }
        }, 
millis);
    }
    
    private 
void timeout() {
        
this.cancel();
        
        
this.timeout true;
        
        if (
this.timeoutListener != null) {
            
this.timeoutListener.timeout();
        }
    }

    public 
void cancel() {
        
this.timer.cancel();
    }

    public 
boolean isTimeout() {
        return 
timeout;
    }
    
    public static 
void main(String[] args) {
        
Timer timer = new Timer();
        
timer.schedule(5000L);
        
        while (!
timer.isTimeout()) {
            try { 
Thread.sleep(1); } catch (Exception e) {}
        }
        
        
System.out.println("-- time-out --");
    }

Con esta clase en vez de usar directamente el timer de java.util debes usar este Timer.

La idea es encapsular la funcionalidad ya que el Timer de java.util tiene muchas mas opciones y yo solo necesitaba una de ellas.

La forma de usarla la peudes ver y probar y en su metodo main.

Saludos
__________________
se despide hasta la proxima
Gonzalo Castillo