Schedule to run a method at periodic time in java -


i have schedule method executed when starting , periodically thereafter @ intervals of 1 minute.

for have done this:

public void init(){     loadconfig(); //method needs executed periodically      timer scheduler = new timer();     scheduler.scheduleatfixedrate(loadconfig(),60000,60000); } 

this giving error , should since first parameter of scheduleatfixedrate of type runnable.

what need advice on, how make loadconfig method runnable , still have executed when loadconfig() before scheduler starts.

as of code structure follows:

public class name {     public void init() {         ...     }     ...     public void loadconfig() {         ...     } } 

edit: have 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 following syntax can create lambda expression, evaluate object of type runnable. when run method of object called loadconfig method called.

scheduler.scheduleatfixedrate(() -> loadconfig(), 60, 60, timeunit.seconds); 

lambda expressions new java 8 feature.

in case works this: arrow, ->, makes expression lambda. () argument list, empty because there no argument run method. loadconfig() after arrow body, works same way method body.

since scheduleatfixedrate expects runnable parameter, target type of expression , lambda become object of type.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -