class is not abstract and does not override abstract method run() in java.util.timertask
I'm trying to use a timer to repeat a function periodically. Now I have to pass inputs to the function, but I get the error "activity is not abstract and does not override abstract method run() in java.util.timertask".
What is the correct practice to pass values to the nested functions called by the timer? Examples online or on the java documentation are too vague.
below there is the skeleton of the code. any idea? also a link to a document where this problem is explained better will be appreciated.
Thanks!
import java.util.*;
public class className {
Timer timer;
public static void main(String args[]) {
//declarations...
initialiseInputs(args);
new executePeriodicActivities(milliseconds); // milliseconds are in "args"
}
public void executePeriodicActivities(int seconds) {
timer = new Timer();
timer.scheduleAtFixedRate(new activity(args), 0, milliseconds);
}
class act开发者_StackOverflow中文版ivity extends TimerTask { //error!
public void run() {
function(args)
if(condition(args)) {timer.cancel();}
}
}
}
Add a constructor to your activity
class that takes a long
parameter. You can then use that value in the run()
method.
class activity extends TimerTask {
private long milis;
public activity(long milis) {
this.milis = milis;
}
public void run() {
function(args)
if(condition(args)) {timer.cancel();}
}
}
Use an anonymous inner class:
import java.util.*;
public class className {
Timer timer;
public static void main(String args[]) {
//declarations...
executePeriodicActivities(milliseconds, args); // milliseconds are in "args"
}
public static void executePeriodicActivities(int seconds, String[] args) {
timer = new Timer();
timer.scheduleAtFixedRate(new TimeTask()
{public void run() {
function(args)
if(condition(args)) {timer.cancel();}
}
}, 0, milliseconds);
}
}
or something similar
精彩评论