How to Pass Arguments to Timertask Run Method

爷,独闯天下 提交于 2019-12-01 18:34:39
sethu

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.

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 
     }
}

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.

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.

class thr extends TimerTask{    
@Override
public void run(){
    System.out.println("task executed task executed .........." );
}               


class service { 
private Timer t;    
public void start(int delay){
    Timer timer=new Timer();
    thr task =new thr();                        
    timer.schedule(task, delay);        
    this.t=timer;
}   
public void stop(){
    System.out.println("Cancelling the task scheduller ");
    this.t.cancel();
}
}

public class task1 {
  public static void main(String[] args) {

    service sv=new service();
    sv.start(1000);
    System.out.println("This will check the asynchronous behaviour ");
    System.out.println("This will check the asynchronous behaviour ");
    System.out.println("This will check the asynchronous behaviour ");
    System.out.println("This will check the asynchronous behaviour ");
    System.out.println("This will check the asynchronous behaviour ");
    sv.stop();

  } 
}

the code above works fine to schedule and reschedule the task you can set and reset the task with a timer function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!