Publi

Pasando argumentos a un TimerTask en Java

Siguiendo con los posts sobre TimerTasks en Java, hoy toca hablar sobre cómo pasar argumentos a un TimerTask, para que éste utilice variables, atributos u objetos desde fuera. Ya vimos algo parecido cuando definíamos el TimerTask de forma implícita o anidada, pero hoy vamos simplemente a crear una clase derivada de TimerTask y pasarle datos a través del constructor.

MyTimerTask.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.TimerTask;

class MyTimerTask extends TimerTask
{
    private int times;
    private String result;
    private int tic=0;

    public MyTimerTask (int times, String arg2)
    {
    this.times=times;
    this.result=arg2;
    }

    public String toString()
    {
    return result;
    }

    public void run()
    {
    System.out.println((tic++%2==0)?"TIC":"TOC");
    if (tic%times==0)
        result+="TEN! ";
    }
}

TimerEx.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Timer;
import java.util.TimerTask;

class TimerEx {
    public static void main(String arglist[]) {
    long lonlon=0;
    Timer timer;
    timer = new Timer();

    TimerTask task = new MyTimerTask(10, "Start: ");

    timer.schedule(task, 10, 1000);
    try
        {
        Thread.sleep(11000);
        }
    catch (Exception e)
        {
        }
    System.out.println(task);
    }
}

En este ejemplo, hemos pasado al TimerTask en su construcción dos argumentos 10, y «Start: «, que serán el número de veces que se tiene que lanzar la tarea antes de escribir en una cadena «TEN! «. Por otro lado, también se ha implementado otro método toString() para que System.out.println() pueda escribir el valor de esa cadena en pantalla.

Es una cosa sencilla, y ya hemos pasado algunos argumentos a la función. Pero, ¿y si queremos pasar un callback para que se ejecute una determinada tarea ?

Primero, vamos a implementar una interfaz para el Callback (MyTimerCallback), luego implementaremos MyTimerTask y tras ello, haremos que TimerEx implemente MyTimerCallback, así podemos situar esta función en la clase principal:

MyTimerCallback.java

1
2
3
4
interface MyTimerCallback
{
    public void timerCallback(MyTimerTask t);
}

MyTimerTask.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.TimerTask;

class MyTimerTask extends TimerTask
{
    private int times;
    private String result="";
    private int tic=0;
    private MyTimerCallback cbClass;

    public MyTimerTask (int times, MyTimerCallback cb)
    {
    this.times=times;
    this.cbClass=cb;
    }

    public String toString()
    {
    return result;
    }

    public void run()
    {
    System.out.println((tic++%2==0)?"TIC":"TOC");
    if (tic%times==0)
        {
        result+="TEN! ";
        cbClass.timerCallback(this);
        }
    }
}

Aquí, en el constructor, pedimos un objeto tipo MyTimerCallback del cual, llamaremos al método timerCallback().

TimerEx.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Timer;
import java.util.TimerTask;

class TimerEx implements MyTimerCallback
{
    public static void main(String arglist[])
    {
    long lonlon=0;
    Timer timer;
    timer = new Timer();

    TimerTask task = new MyTimerTask(10, new TimerEx());

    timer.schedule(task, 10, 1000);
    }

    public void timerCallback(MyTimerTask t)
    {
    System.out.println(t);
    }
}

Desde TimerEx, pasamos un nuevo objeto TimerEx (ya que el método main es estático y la clase no se ha instanciado, debemos instanciarla, por eso el new TimerEx()).

Ahora, siempre que se ejecuten 10 tics, llamaremos a timerCallback(). Y, por supuesto, podríamos haber hecho una clase implícita aquí, como vemos en este último ejemplo de TimerEx.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Timer;
import java.util.TimerTask;

class TimerEx implements MyTimerCallback
{
    public static void main(String arglist[])
    {
    long lonlon=0;
    Timer timer;
    timer = new Timer();

    TimerTask task = new MyTimerTask(10, new MyTimerCallback()
        {
        public void timerCallback(MyTimerTask t)
        {
            System.out.println("Inner class: "+t);
        }
        });

    timer.schedule(task, 10, 100);
    }

    public void timerCallback(MyTimerTask t)
    {
    System.out.println(t);
    }
}

Foto: Rob & Stephanie Levy (Flickr) CC-by

También podría interesarte....

There are 4 comments left Ir a comentario

  1. Pingback: BlogESfera.com /

  2. Sherlock Amity /
    Usando Google Chrome Google Chrome 75.0.3770.80 en Windows Windows NT

    Your post is fascinating and remarkable in its format! I find it to be quite useful and informative, and I eagerly await your next communication. tetris unblocked

  3. Mike Rooney /
    Usando Google Chrome Google Chrome 110.0.0.0 en Windows Windows NT

    Thanks for a wonderful share. Here is the great example related to you blog. Jack Torrance Corduroy Jacket

  4. Andrew Mark /
    Usando Google Chrome Google Chrome 111.0.0.0 en Windows Windows NT

    Your post content is being interested by a lot of people, I am very impressed with your post. I hope to receive more good articles.
    Yellowstone Merchandise

Leave a Reply