2009-08-03 39 views
21

No soy un experto, solo un principiante. Por lo tanto, le pido amablemente que escriba un código para mí.Llamar a una función cada 10 minutos

Si tengo dos clases, CLASS A y CLASS B, y dentro de CLASS B hay una función llamada funb(). Deseo llamar a esta función desde CLASS A cada diez minutos.

Ya me diste algunas ideas, pero no las entendí del todo.

¿Puedes publicar algún código de ejemplo, por favor?

+4

creo que en algún lugar detrás de esto hay una pregunta válida; es por eso que lo edité. – balpha

+1

@balpha: trabajó un poco de magia allí: o –

Respuesta

9
import java.util.Date; 

import java.util.Timer; 

import java.util.TimerTask; 

public class ClassExecutingTask { 

    long delay = 10 * 1000; // delay in milliseconds 
    LoopTask task = new LoopTask(); 
    Timer timer = new Timer("TaskName"); 

    public void start() { 
     timer.cancel(); 
     timer = new Timer("TaskName"); 
     Date executionDate = new Date(); // no params = now 
     timer.scheduleAtFixedRate(task, executionDate, delay); 
    } 

    private class LoopTask extends TimerTask { 
     public void run() { 
      System.out.println("This message will print every 10 seconds."); 
     } 
    } 

    public static void main(String[] args) { 
     ClassExecutingTask executingTask = new ClassExecutingTask(); 
     executingTask.start(); 
    } 


} 
+0

Simplemente cambie la demora .... –

+0

TimerTask es obsoleto y se ha reemplazado con ExecutorService y las implementaciones asociadas. – skaffman

+2

¿De verdad? No puedo encontrar nada que diga eso. Me interesaría ver tus fuentes. Gracias ! :) –

23

Tener un vistazo a la ScheduledExecutorService:

Aquí es una clase con un método que establece una ScheduledExecutorService para que suene cada diez segundos durante una hora:

import static java.util.concurrent.TimeUnit.*; 
class BeeperControl { 
    private final ScheduledExecutorService scheduler = 
     Executors.newScheduledThreadPool(1); 

    public void beepForAnHour() { 
     final Runnable beeper = new Runnable() { 
       public void run() { System.out.println("beep"); } 
      }; 
     final ScheduledFuture<?> beeperHandle = 
      scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); 
     scheduler.schedule(new Runnable() { 
       public void run() { beeperHandle.cancel(true); } 
      }, 60 * 60, SECONDS); 
    } 
} 
2
public class datetime { 

    public String CurrentDate() { 

     java.util.Date dt = new java.util.Date(); 
     java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     String currentTime = sdf.format(dt); 
     return currentTime; 

    } 

    public static void main(String[] args) { 
     class SayHello extends TimerTask { 

      datetime thisObj = new datetime(); 

      public void run() { 
       String todaysdate = thisObj.CurrentDate(); 
       System.out.println(todaysdate); 
      } 
     } 
     Timer timer = new Timer(); 
     timer.schedule(new SayHello(), 0, 5000); 
    } 
} 
6

Try esta. Repetirá la función run() cada minuto establecido. Para cambiar los minutos establecidos, cambie la variable MINUTOS

int MINUTES = 10; // The delay in minutes 
Timer timer = new Timer(); 
timer.schedule(new TimerTask() { 
    @Override 
    public void run() { // Function runs every MINUTES minutes. 
     // Run the code you want here 
     CLASSB.funcb(); // If the function you wanted was static 
    } 
}, 0, 1000 * 60 * MINUTES); 
    // 1000 milliseconds in a second * 60 per minute * the MINUTES variable. 

¡No olvide hacer las importaciones!

import java.util.Timer; 
import java.util.TimerTask; 

Para obtener más información, vaya a:

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

Cuestiones relacionadas