How to Pass Arguments to Timertask Run Method

19,871

Solution 1

You will need to extend the TimerTask and create a constructor and/or setter fields.. Then set the values you want before scheduling the TimerTask for execution.

Solution 2

You can write you own class which extends from TimerTask class and you can override run method.

class MyTimerTask extends TimerTask  {
     String param;

     public MyTimerTask(String param) {
         this.param = param;
     }

     @Override
     public void run() {
         // You can do anything you want with param 
     }
}

Solution 3

It's not possible to change the signature of the run() method.

However, you may create a subclass of TimerTask and give it some kind of initialize-method. Then you can call the new method with the arguments you want, save them as fields in your subclass and then reference those initialized fields in the run()-method:

abstract class MyTimerTask extends TimerTask
{
  protected String myArg = null;
  public void init(String arg)
  {
    myArg = arg;
  }
}

...

MyTimerTask timert = new MyTimerTask() 
{
  @Override
  public void run() 
  {
       //do something
       System.out.println(myArg);
  }
} 

...

timert.init("Hello World!");
new Thread(timert).start();

Make sure to set the fields' visibilities to protected, because private fields are not visible to (anonymous) subclasses of MyTimerTask. And don't forget to check if your fields have been initialized in the run() method.

Solution 4

The only way to do this is to create your own class that extends TimerTask and pass arguments to its constructor or call its setters. So, the task will "know" its arguments from the moment of its creation.

Moreover if it provides setters you can modify the task configuration even later, after the task has been already scheduled.

Share:
19,871

Related videos on Youtube

sjtaheri
Author by

sjtaheri

Updated on June 04, 2022

Comments

  • sjtaheri
    sjtaheri almost 2 years

    I have a method and I want it to be scheduled for execution in later times. The scheduling time and method's arguments depend on user inputs.

    I already have tried Timers, but I have a question.

    How could It be possible to pass arguments to Java TimerTask run method ?

    TimerTask timert = new TimerTask() 
    {
         @Override
         public void run() 
         {
               //do something
         }
    }