如何将参数传递给Timertask Run方法

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

我已经尝试过Timers,但我有一个问题。

怎么可能将参数传递给Java TimerTask运行方法?

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

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

您可以编写自己的类,它从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 } } 

执行此操作的唯一方法是创建自己的类,该类扩展TimerTask并将参数传递给其构造函数或调用其setter。 因此,任务将从其创建的那一刻起“知道”它的论点。

此外,如果它提供了setter,您甚至可以在已经安排任务之后修改任务配置。

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

但是,您可以创建TimerTask的子类并为其提供某种初始化方法。 然后,您可以使用所需的参数调用new方法,将它们保存为子类中的字段,然后在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(); 

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

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

上面的代码可以很好地安排和重新安排您可以设置的任务,并使用计时器function重置任务