I have to schedule a method to be executed when starting and periodically thereafter at intervals of 1 minute.
For that I have done this:
public void init(){
loadConfig(); //method which needs to be executed periodically
Timer scheduler = new Timer();
scheduler.scheduleAtFixedRate(loadConfig(),60000,60000);
}
This is giving an error and it should since the first parameter of scheduleAtFixedRate
is of type Runnable
.
What I need advice on, is how to make my loadConfig
method Runnable
and still have it executed when I do loadConfig()
before the scheduler starts.
As of now code structure is as follows:
public class name {
public void init() {
...
}
...
public void loadConfig() {
...
}
}
EDIT: This is what I have already tried
public void init(){
loadConfig();
Timer scheduler = new Timer();
scheduler.scheduleAtFixedRate(task,60000,60000);
}
final Runnable task = new Runnable() {
public void run() {
try {
loadConfig();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Using the following syntax you can create a lambda expression, which will evaluate to an object of type
Runnable
. When therun
method of that object is called theloadConfig
method will get called.Lambda expressions is a new Java 8 feature.
In this case it works like this: The arrow,
->
, makes the expression into a lambda.()
is the argument list, which is empty because there are no argument to therun
method. TheloadConfig()
after the arrow is the body, which works the same way as a method body.Since
scheduleAtFixedRate
expects aRunnable
as a parameter, that will be the target type of the expression and the lambda will become an object of that type.