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 Timers, but I have a question.
How could It be possible to pass arguments to Java TimerTask run met开发者_如何学JAVAhod ?
TimerTask timert = new TimerTask()
{
@Override
public void run()
{
//do something
}
}
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
}
}
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.
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.
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.
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
精彩评论