如何向TimerTask的Run方法传递参数

7

我有一个方法,希望可以安排在之后的某个时间执行。调度时间和方法参数取决于用户输入。

我已经尝试过定时器,但是还有一个问题。

如何将参数传递给Java TimerTask的run方法?

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

将参数设置为字段,然后您可以在运行方法中获取它。 - Neifen
5个回答

31

你可以编写一个继承自TimerTask类的类,并重写run方法。

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

+1 对于详细的示例,但请将“String”一词大写。 - Eli Acherkan

8
你需要扩展TimerTask并创建构造函数和/或setter字段。然后在安排执行TimerTask之前设置所需的值。

2

无法更改run()方法的签名。

但是,您可以创建一个TimerTask的子类并为其提供某种初始化方法。然后,您可以使用想要的参数调用新方法,在子类中保存它们作为字段,然后在run()方法中引用这些已初始化的字段:

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();

确保将字段的可见性设置为protected,因为private字段对MyTimerTask的(匿名)子类不可见。并且不要忘记在run()方法中检查您的字段是否已初始化。


1
唯一的方法是创建一个扩展TimerTask的自定义类,并将参数传递给它的构造函数或调用其setter。因此,任务将从创建时就“知道”其参数。
此外,如果它提供了setter,您甚至可以在任务已经被安排后修改任务配置。

0
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();

  } 
}

上述代码可以很好地安排和重新安排任务,您可以使用定时器函数设置和重置任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接