我有一个方法,我希望它被安排在以后执行。调度时间和方法的参数取决于用户输入。
我已经尝试过 Timers,但我有一个问题。
怎么可能将参数传递给 Java TimerTask 运行方法?
TimerTask timert = new TimerTask()
{
@Override
public void run()
{
//do something
}
}
我有一个方法,我希望它被安排在以后执行。调度时间和方法的参数取决于用户输入。
我已经尝试过 Timers,但我有一个问题。
怎么可能将参数传递给 Java TimerTask 运行方法?
TimerTask timert = new TimerTask()
{
@Override
public void run()
{
//do something
}
}
您可以编写自己的类,该类从 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
并创建构造函数和/或设置器字段。然后在安排TimerTask
执行之前设置所需的值。
无法更改run()
方法的签名。
但是,您可以创建 TimerTask 的子类并为其提供某种初始化方法。然后您可以使用所需的参数调用新方法,将它们保存为子类中的字段,然后在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()
方法中初始化。
做到这一点的唯一方法是创建您自己的类来扩展 TimerTask 并将参数传递给它的构造函数或调用它的 setter。因此,任务从创建的那一刻起就“知道”它的论点。
此外,如果它提供设置器,您甚至可以在已经安排任务之后修改任务配置。
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();
}
}
上面的代码可以很好地安排和重新安排您可以使用计时器功能设置和重置任务的任务