How to Pass Arguments to Timertask Run Method

后端 未结 5 739
悲&欢浪女
悲&欢浪女 2021-01-12 21:45

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 T

5条回答
  •  孤街浪徒
    2021-01-12 22:02

    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.

提交回复
热议问题